How to get a list of dtypes from a numpy structured array?

726 views Asked by At

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

There are 2 answers

0
Kermit On

Or, as @hpaulj hinted, in one step:

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

['float64', 'float64']

2
Kermit On

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']