本文介绍了numpy,数组没有自己的数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to use resize on an array in this way:

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

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

and the output is Ok!(I meant that there was no error). But when I run this code:

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

it gave rise to an error, saying that, ValueError: cannot resize this array: it does not own its data

我的问题:为什么在应用reshape之后,数组的所有权被更改了?所有权授予给谁! reshape不会创建新的内存,而是在同一阵列内存上执行其操作!那么所有权为什么会改变?

My question: why after applying reshape the ownership of array is changed? The ownership is granted to whom !? The reshape does not create a new memory and it is performing its operation on the same array memory! So why the ownership will change?

我阅读了 np.reshape ndarray.resize 文件,但我不明白原因.我阅读了这篇文章.在应用resize方法之前,我可以始终检查ndarray.flags.

I read np.reshape and ndarray.resize doc but I can not understand the reason. I read this post. I can check ndarray.flags always before applying the resize method.

推荐答案

让我们从以下内容开始:

Lets start with the following:

>>> 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.调用resize函数(如ndarray.resize)尝试更改数组 ,因为b只是a的视图,从resize定义开始是不允许的:

I can see here that array b is not its own array, but simply a view of a (just another way to understand the "OWNDATA" flag). To put it simply both a and b reference the same data in memory, but b is viewing a with a different shape. Calling the resize function like ndarray.resize tries to change the array in place, as b is just a view of a this is not permissible as from the resize definition:


要避开您的问题,您可以从numpy(不是ndarray的属性)中调用resize,它将检测到此问题并自动复制数据:


To circumvent your issue you can call resize from numpy (not as an attribute of a ndarray) which will detect this issue and copy the data automatically:

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

正如朱卓CT正确提到的,np.resizendarray.resize用两种不同的方式添加数据.若要将预期的行为重现为ndarray.resize,则必须执行以下操作:

As CT Zhu correctly mention np.resize and ndarray.resize add data in two different ways. To reproduce expected behavior as ndarray.resize you would have to do the following:

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

这篇关于numpy,数组没有自己的数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:39