1

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?

1
  • dt = np.dtype([('n', 'i4'), *zip('xyz', ['f8']*3)])? Commented Jan 15, 2022 at 13:45

2 Answers 2

1

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')])
Sign up to request clarification or add additional context in comments.

Comments

0

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} )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.