2

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.

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, didn't know about using ravel to avoid the extra length-1 axis.

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.