0

I am trying to learn how to use numpy's structured arrays. Specifically, I was trying to add information to more than one field at a time. I tried:

import numpy as np

numrec = np.zeros(8, dtype=[('col0', 'int16'), ('col1', 'int16'),
                            ('col2', 'int16'), ('col3', 'int16')])

numrec[['col1','col2']][0:2] = [(3,5), (1,8)]
print numrec

The above does not work. The values are not added to the columns specified. What is surprising is that I do not get any error when I run it. Can someone please explain what is happening?

Thanks.

Curious2learn
  • 31,692
  • 43
  • 108
  • 125

1 Answers1

9

You are setting values on a temporary.

numrec[["col1", "col2"]]

returns a copy of the array. You can see this by the OWNDATA flag.

>>> numrec[["col1", "col2"]].flags["OWNDATA"]
True

When you index a numpy array with a list, numpy returns a copy of the data. It has to be a copy, because, in general, the list may not resolve to a regular, ordered view of the underlying data. (This holds for any numpy array, not just structured arrays.)

Compare

>>> numrec[["col1"]].flags["OWNDATA"]
True
>>> numrec["col1"].flags["OWNDATA"]
False

Also, if a numpy array is a view, the base member holds the underlying array.

>>> id(numrec["col1"].base) == id(numrec)
True
AFoglia
  • 7,968
  • 3
  • 35
  • 51
  • 5
    spot on. It might also be worth mentioning that this is true for all "fancy indexed" arrays, not just structured arrays. And I'll put a link to this related recent post here: http://stackoverflow.com/questions/5127991/can-i-get-a-view-of-a-numpy-array-at-specified-indexes-a-view-from-fancy-index – Paul Mar 04 '11 at 21:34
  • Thanks!! I did not know this. So, if I have two lists `listone` (of length 3) and `listwo` (of length 3) can I update first three elements in `'col1'` and `'col2'` of `numrec` to equal these lists simultaneously. I know I can do `numrec['col1'][0:3] = listone` and `numrec['col2'][0:3] = listtwo`. But can I do it together in one command. Thanks. – Curious2learn Mar 04 '11 at 22:33
  • Paul, I may not have emphasized it, but that's what I didn't say "When you index a numpy structured array..." Anyway, I could have made it clearer. So I just added a parenthetical to that effect. – AFoglia Mar 04 '11 at 22:57
  • Curious2learn, I don't think there is a way to do what you want in one simple command, though I would appreciate someone proving me wrong. – AFoglia Mar 05 '11 at 00:53