Home > other >  How to create a uniform structured array in numpy?
How to create a uniform structured array in numpy?

Time:01-16

I could create the following strucutured array in numpy:

dt = np.dtype([('n', 'i4'),('x', 'f8'), ('y', 'f8'), ('z', 'f8')])
arr = np.array((1, 5.0, 6.0, 7.0)) 

This creates the array:

array((1, 5., 6., 7.), dtype=[('n', '<i4'), ('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

In dt the last three columns are all floats f8 is there a shorter way to declare dt when there are multiple consecutive columns of the same type?

CodePudding user response:

Not faster, but you can create an helper function to generate dtype:

def gen_dtype(names, override=None, default='f8'):
    d = dict(zip(names, [default]*len(names)))
    d.update(override)
    return np.dtype(list(d.items()))

dt  = gen_dtype(list('nxyz'), {'n': 'i4'})

Output:

>>> dt
dtype([('n', '<i4'), ('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

CodePudding user response:

An alternative method is to use the dictionary format to define the dtype:

dt2 = np.dtype( {'names': ['n','x','y','z'],
                 'formats': ['i4']   ['f8']*3} )
  •  Tags:  
  • Related