python - 为什么不复制 numpy 数组会更改数据属性?

标签 python arrays numpy numpy-ndarray

正如我下面的 MWE 所示,调用 np.array(a, copy=False)在现有阵列上 a返回与预期完全一样的东西,除了 .data属性好像不一样。怎么会这样?

>>> 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一边看一边属性变化!

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

最佳答案

如果您键入:

help(a.data)

您会看到它并没有完全返回您所期望的:
class memoryview(object)
 |  memoryview(object)
 |  
 |  Create a new memoryview object which references the given object.
 |  
 |  Methods defined here:
 |  


它创建了一个 的内存 View 。引用资料 那个物体。如果你想要内存地址使用 id :
id(a) == id(b)
True

注意:
id(a) is id(b)
False

因为id(a)也返回一个整数和 id(b) 以及它们的内存地址 不是 尽管它们的值是相同的。

如果你想要十六进制内存:
hex(id(a))

此外,来自 NumPy 文档:numpy.ndarray.data (我真的不知道为什么这个 .data 有用但它存在)

关于python - 为什么不复制 numpy 数组会更改数据属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61102237/

相关文章:

Python 2.5 Windows 二进制文件?

php - 正确显示关联数组的结果 Laravel/PHP

javascript - 有条件地创建数组(Javascript)

python - ValueError : all the input array dimensions for the concatenation axis must match exactly, 但沿维度 2,索引 0 处的数组大小为 3

python - 我无法抓取网站的 div 参数(scrapy)

python - 从字符串更改 int 和 string

python - RE 在 pythex 中有效,但在 python 中无效

java - 删除重复 JAVA 数组的最佳实现

python - 如何在一行中打印一个 numpy.array?

linux - 尝试安装 Numpy : SystemError: Cannot compile 'Python.h'