带副本的 Numpy 数组赋值 [英] Numpy array assignment with copy

查看:29
本文介绍了带副本的 Numpy 数组赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我们有一个 numpy 数组 A,并且我们想要一个 numpy 数组 B 和相同的元素.

For example, if we have a numpy array A, and we want a numpy array B with the same elements.

以下(见下文)方法有什么区别?什么时候分配额外的内存,什么时候不分配?

What is the difference between the following (see below) methods? When is additional memory allocated, and when is it not?

  1. B = A
  2. B[:] = A(同 B[:]=A[:]?)
  3. numpy.copy(B, A)

推荐答案

三个版本的作用不同:

  1. B = A

这会将新名称 B 绑定到已命名为 A 的现有对象.之后它们引用同一个对象,因此如果您在适当的位置修改一个,您也会通过另一个看到更改.

This binds a new name B to the existing object already named A. Afterwards they refer to the same object, so if you modify one in place, you'll see the change through the other one too.

B[:] = A(同B[:]=A[:]?)

这会将A 中的值复制到现有数组B 中.这两个数组必须具有相同的形状才能工作.B[:] = A[:] 做同样的事情(但 B = A[:] 会做更像 1 的事情).

This copies the values from A into an existing array B. The two arrays must have the same shape for this to work. B[:] = A[:] does the same thing (but B = A[:] would do something more like 1).

numpy.copy(B, A)

这不是合法的语法.您可能的意思是 B = numpy.copy(A).这与 2 几乎相同,但它创建了一个新数组,而不是重用 B 数组.如果没有其他引用之前的 B 值,最终结果将与 2 相同,但在复制过程中会临时使用更多内存.

This is not legal syntax. You probably meant B = numpy.copy(A). This is almost the same as 2, but it creates a new array, rather than reusing the B array. If there were no other references to the previous B value, the end result would be the same as 2, but it will use more memory temporarily during the copy.

或者你的意思是numpy.copyto(B, A),这是合法的,相当于2?

Or maybe you meant numpy.copyto(B, A), which is legal, and is equivalent to 2?

这篇关于带副本的 Numpy 数组赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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