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.

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

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: stackoverflow.com/questions/5127991/…
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.
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.
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.

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.