2

How can I get a list of dtypes from a numpy structured array?

Create example structured array:

arr = np.array([[1.0, 2.0],[3.0, 4.0]])

dt = {'names':['ID', 'Ring'], 'formats':[np.double, np.double]}
arr.dtype = dt
>>> arr
array([[(1., 2.)],
       [(3., 4.)]], dtype=[('ID', '<f8'), ('Ring', '<f8')])

On one hand, it's easy to isolate the column names.

>>> arr.dtype.names
('ID', 'RING')

However, ironically, none of the dtype attributes seem to reveal the individual dtypes.

2

2 Answers 2

2

Discovered that, despite not having dictionary methods like .items(), you can still call dtype['<column_name>'].

column_names = list(arr.dtype.names)
dtypes = [str(arr.dtype[n]) for n in column_names]
>>> dtypes

['float64', 'float64']
Sign up to request clarification or add additional context in comments.

1 Comment

dtype.fields is a dict, with name as key, and (dtype, offset) as value.
0

Or, as @hpaulj hinted, in one step:

>>> [str(v[0]) for v in arr.dtype.fields.values()]

['float64', 'float64']

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.