Numpy,数组没有自己的数据?

2024-05-23 19:13:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用这种方式在数组上使用resize

a = np.array([1,2,3,4,5,6], dtype=np.uint8)
a.resize(4,2)
print a 

输出正常!(我的意思是没有错误)。但是当我运行这个代码时:

a = np.array([1,2,3,4,5,6], dtype=np.uint8).reshape(2,3)
a.resize(4,2)
print a 

它产生了一个错误,说,ValueError: cannot resize this array: it does not own its data

我的问题是:为什么在应用reshape之后数组的所有权发生了更改?所有权授予谁!?reshape不创建新内存,它正在同一个数组内存上执行操作!那为什么所有权会改变呢?

我读了np.reshapendarray.resize文档,但我不明白原因。我读过this post。我可以在应用resize方法之前检查ndarray.flags


Tags: 内存错误np方式数组thisarrayprint
1条回答
网友
1楼 · 发布于 2024-05-23 19:13:22

让我们从以下内容开始:

>>> a = np.array([1,2,3,4,5,6], dtype=np.uint8)
>>> b = a.reshape(2,3)
>>> b[0,0] = 5
>>> a
array([5, 2, 3, 4, 5, 6], dtype=uint8)

我在这里可以看到数组b不是它自己的数组,而是a的视图(只是理解“OWNDATA”标志的另一种方式)。简单地说,ab引用内存中的相同数据,但是b是用不同的形状查看a。调用像ndarray.resize这样的resize函数将尝试更改数组的位置,因为b只是a的视图。从resize定义来看,这是不允许的:

The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory.


为了避免您的问题,您可以从numpy调用resize(不是ndarray的属性),后者将检测此问题并自动复制数据:

>>> np.resize(b,(4,2))
array([[5, 2],
       [3, 4],
       [5, 6],
       [5, 2]], dtype=uint8)

编辑:正如CT-Zhu正确地提到的,np.resizendarray.resize以两种不同的方式添加数据。要将预期行为重新生成为ndarray.resize,必须执行以下操作:

>>> c = b.copy()
>>> c.resize(4,2)
>>> c
array([[5, 2],
       [3, 4],
       [5, 6],
       [0, 0]], dtype=uint8)

相关问题 更多 >