如何判断NumPy创建的是视图还是副本?

2024-04-29 06:44:16 发布

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

对于一个最小的工作示例,让我们数字化一个二维数组。numpy.digitize需要一维数组:

import numpy as np
N = 200
A = np.random.random((N, N))
X = np.linspace(0, 1, 20)
print np.digitize(A.ravel(), X).reshape((N, N))

现在documentation says

... A copy is made only if needed.

在这种情况下,我如何知道是否需要ravel副本?一般来说-有没有方法可以确定某个特定操作是创建副本还是视图?


Tags: importnumpy示例documentationasnp副本random
2条回答

这个问题与我刚才问的question非常相似:

您可以检查base属性。

a = np.arange(50)
b = a.reshape((5, 10))
print (b.base is a)

然而,这并不完美。您还可以使用np.may_share_memory检查它们是否共享内存。

print (np.may_share_memory(a, b))

还可以检查flags属性:

print (b.flags['OWNDATA'])  #False -- apparently this is a view
e = np.ravel(b[:, 2])
print (e.flags['OWNDATA'])  #True -- Apparently this is a new numpy object.

但这最后一个对我来说有点可疑,虽然我不太明白为什么。。。

reshape的文档中,有一些关于在无法创建视图时如何确保异常的信息:

It is not always possible to change the shape of an array without copying the data. If you want an error to be raised if the data is copied, you should assign the new shape to the shape attribute of the array:

>>> a = np.zeros((10, 2))
# A transpose make the array non-contiguous
>>> b = a.T
# Taking a view makes it possible to modify the shape without modiying the
# initial object.
>>> c = b.view()
>>> c.shape = (20)
AttributeError: incompatible shape for a non-contiguous array



这并不完全是对你问题的回答,但在某些情况下,它可能同样有用。

相关问题 更多 >