siamii
siamii

Reputation: 24084

How to convert a ndarray to a structured array?

I have a regular float ndarray with shape (100,50). How can I give names to the first two columns, i.e. 'idx1' and 'idx2', and 'data' to the rest of the columns.

Upvotes: 2

Views: 729

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114781

You can use the view method. Here's an example, using an array with shape (3, 5) for the demo:

In [21]: x
Out[21]: 
array([[  0.,   1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.,   9.],
       [ 10.,  11.,  12.,  13.,  14.]])

In [22]: y = x.ravel().view(dtype=[('idx1', float), ('idx2', float), ('data', float, 3)])

In [23]: y['idx1']
Out[23]: array([  0.,   5.,  10.])

In [24]: y['data']
Out[24]: 
array([[  2.,   3.,   4.],
       [  7.,   8.,   9.],
       [ 12.,  13.,  14.]])

In [25]: y['data'][1]
Out[25]: array([ 7.,  8.,  9.])

Note that y is a 1-D array; it has shape (3,). If you change the conversion to y = x.view(...) (i.e. don't ravel x), y will have have (3,1), and y['idx1'] will have shape (3,1).

Upvotes: 7

Related Questions