不复制numpy数组如何改变数据属性? [英] How come not-copying a numpy array changes the data attribute?
问题描述
如下我的MWE所示,在现有数组 a
np.array(a,copy = False) >返回的行为与预期的完全一样,除了 之外, .data
属性似乎有所不同。
As my MWE below shows, calling np.array(a, copy=False)
on an existing array a
returns something that behaves exactly as expected, except that the .data
attributes seem to differ. How can this be?
>>> a # My original array
array([2])
>>> b = np.array(a, copy=False) # Not-a-copy of the original array
>>> b is a # The Python objects seem to be identical
True
>>> b.data is a.data # But their .data attributes aren't??
False
>>> a.data
<memory at 0x7f82ebd757c8>
>>> b.data
<memory at 0x7f82ebd75888>
>>> b
array([2])
>>> a
array([2])
>>> a[:] = 3 # Changing a indeed also changes b
>>> a
array([3])
>>> b
array([3])
>>> a.data
<memory at 0x7f82ebd757c8>
>>> b.data
<memory at 0x7f82ebd75888>
编辑
在玩耍时,我什至发现 .data
属性在查看时会发生变化!
While playing around, I even found that the .data
attribute changes while looking at it!
>>> a.data is a.data # a.data isn't equal to itself?!
False
>>> a.data
<memory at 0x7f82ebd75948>
>>> a.data
<memory at 0x7f82ebd75888> # A different value than a minute ago
>>> a.data
<memory at 0x7f82ebd75948>
>>> a.data
<memory at 0x7f82ebd75888>
>>> a.data
<memory at 0x7f82ebd75948>
>>> a.data
<memory at 0x7f82ebd75888>
>>> a.data
<memory at 0x7f82ebd75948>
>>> a.data
<memory at 0x7f82ebd75888>
>>> a.data
<memory at 0x7f82ebd75948>
推荐答案
In [33]: a = np.array([2])
In [34]: b = np.array(a, copy=False)
一种易于理解的共享数据缓冲区检查方法是 __ array_interface __
字典。
A nice human-readable way of checking for shared data buffer is the __array_interface__
dictionary.
In [36]: a.__array_interface__
Out[36]:
{'data': (69508768, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (1,),
'version': 3}
In [37]: b.__array_interface__
Out[37]:
{'data': (69508768, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (1,),
'version': 3}
a.data
可以用来创建一个新数组,否则不是很有用。甚至对于大多数用途而言,这种用法也太低级了:
a.data
can be used to make a new array, but otherwise isn't very useful. And even this use is too low-level for most purposes:
In [44]: c = np.ndarray(shape=(1,1), dtype=int, buffer=a.data)
In [45]: c
Out[45]: array([[2]])
In [46]: c.__array_interface__
Out[46]:
{'data': (69508768, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (1, 1),
'version': 3}
这篇关于不复制numpy数组如何改变数据属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!