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

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

问题描述

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

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

现在文档说:

... 仅在需要时进行复制.

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

推荐答案

这个问题与一个问题非常相似我前阵子问过:

This question is very similar to a question that I asked a while back:

您可以检查 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))

您还可以检查 flags 属性:

There's also the flags attribute that you can check:

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天全站免登陆