pythonnumpystructured-array

numpy Structured arrays append and remove records


let's say we have this structured array :

x = np.array([('Rex', 9, 81.0), ('Fido', 3, 27.0)],
dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')])

how to delete the first row :('Rex', 9, 81.0) ? and how add another row ??


Solution

  • Are you wanting this: (with np.insert)

    >>> x = np.array([('Rex', 9, 81.0), ('Fido', 3, 27.0)],dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')])
    
    >>> y = np.array([('sam', 10, 100.0)],dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')])
    
    >>> np.insert(x[1:],0,y)
    array([('sam', 10, 100.), ('Fido',  3,  27.)],
          dtype=[('name', '<U10'), ('age', '<i4'), ('weight', '<f4')])
    

    Or with np.append and np.delete:

    >>> x = np.delete(x, 1, axis=0)
    >>> np.append(x, y, axis=0)
    array([('Rex',  9,  81.), ('sam', 10, 100.)],
          dtype=[('name', '<U10'), ('age', '<i4'), ('weight', '<f4')])