我如何知道NumPy是创建视图还是副本? [英] How can I tell if NumPy creates a view or a copy?

查看:209
本文介绍了我如何知道NumPy是创建视图还是副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For a minimal working example, let's digitize a 2D array. numpy.digitize requires a 1D array:

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

=http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html>文档说:

Now the documentation says:


...只有在需要时才复印。

... A copy is made only if needed.

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

How do I know if the ravel copy it is "needed" in this case? In general - is there a way I can determine if a particular operation creates a copy or a view?

推荐答案

类似于我以前问的问题

您可以检查 base 属性。

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

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

However, that's not perfect. You can also check to see if they share memory using np.may_share_memory.

print (np.may_share_memory(a, b))

检查:

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.

但这最后一个似乎对我有点腥,虽然我不能把我的手指为什么...

But this last one seems a little fishy to me, although I can't quite put my finger on why...

这篇关于我如何知道NumPy是创建视图还是副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆