开发者

numpy structured arrays: help understanding output

开发者 https://www.devze.com 2023-02-15 02:07 出处:网络
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:

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 ex开发者_开发技巧plain what is happening?

Thanks.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号