简体   繁体   English

按值或按引用与my_ndarray […]

[英]by-value or by-reference with my_ndarray[…]

I try to copy an numpy.ndarray by value, the following way: 我尝试通过值通过以下方式复制numpy.ndarray

my_copy = my_original[...]

However, this seems to assign the reference. 但是,这似乎分配了参考。

While the following way does actually copy the data: 尽管以下方式实际上可以复制数据:

my_copy[...] = my_original

This confuses me, because I always assumed that [...] will just refer to the plain data, so that both ways should work. 这让我感到困惑,因为我一直认为[...]只引用纯数据,所以两种方法都应该起作用。

What exactly is the rule and the reason for those behaviors? 这些行为的规则和原因到底是什么? What's the best practice to copy data in Numpy? 在Numpy中复制数据的最佳实践是什么?

You are mixing two concepts, the first one: 您正在混合两个概念,第一个:

y = x[...]

just assigns a view of x to the variable name y . 只是将x视图分配给变量名y x and y are not identical but they share the same memory (so changes will propagate to the other one). xy不同,但是它们共享相同的内存(因此更改将传播到另一个内存)。

y[...] = x

Assigns the values of x to an existing array y . x的值分配给现有数组y This will copy the values if x and y don't share memory! 如果xy不共享内存,这将复制值!

In general you should just use np.copy or np.ndarray.copy when you want to create a new copy of an array. 通常,当您要创建数组的新副本时,只应使用np.copynp.ndarray.copy If you want to copy an array into an existing array you need to make sure you don't lose the reference to the array you want to copy the values into. 如果要将数组复制到现有数组 ,则需要确保不会丢失对要复制值的数组的引用。 So you must not re-assign to the variable name (so y[:] = x or y[...] = x are fine because you work on the contents of y - but y = x just "overwrites" the variable name, it does not modify the contents of the original y ). 因此,您不能重新分配变量名 (所以y[:] = xy[...] = x很好,因为您处理y的内容-但是y = x只是“覆盖”了变量名) ,它不会修改原始y的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM