numpy的就地操作(例如,"+ =")如何工作? [英] How do numpy's in-place operations (e.g. `+=`) work?
问题描述
基本问题是:a[i] += b
在执行引擎盖时会发生什么?
给出以下内容:
import numpy as np
a = np.arange(4)
i = a > 0
i
= array([False, True, True, True], dtype=bool)
我了解:
-
a[i] = x
与a.__setitem__(i, x)
相同,后者直接分配给i
指示的项目
-
a += x
与a.__iadd__(x)
相同,就地进行加法
但是当我这样做时会发生什么:
a[i] += x
特别是:
- 与
a[i] = a[i] + x
相同吗? (这不是就地操作) - 如果
i
是,在这种情况下是否有所不同:-
int
索引,或 -
ndarray
,或 - 一个
slice
对象
-
背景
我开始研究此问题的原因是在处理重复索引时遇到了非直觉的行为:
a = np.zeros(4)
x = np.arange(4)
indices = np.zeros(4,dtype=np.int) # duplicate indices
a[indices] += x
a
= array([ 3., 0., 0., 0.])
关于此问题
的更有趣的东西a>.
您需要意识到的第一件事是a += x
并不完全映射到a.__iadd__(x)
,而是映射到a = a.__iadd__(x)
.请注意,文档专门说就地运算符返回其结果,但这并没有不必是self
(尽管实际上通常是).这意味着a[i] += x
琐碎地映射到:
a.__setitem__(i, a.__getitem__(i).__iadd__(x))
因此,技术上的添加是就地发生的,但仅在临时对象上发生.但是,创建的临时对象仍然可能比调用__add__
的对象少.
The basic question is: What happens under the hood when doing: a[i] += b
?
Given the following:
import numpy as np
a = np.arange(4)
i = a > 0
i
= array([False, True, True, True], dtype=bool)
I understand that:
a[i] = x
is the same asa.__setitem__(i, x)
, which assigns directly to the items indicated byi
a += x
is the same asa.__iadd__(x)
, which does the addition in place
But what happens when I do:
a[i] += x
Specifically:
- Is this the same as
a[i] = a[i] + x
? (which is not an in-place operation) - Does it make a difference in this case if
i
is:- an
int
index, or - an
ndarray
, or - a
slice
object
- an
Background
The reason I started delving into this is that I encountered a non-intuitive behavior when working with duplicate indices:
a = np.zeros(4)
x = np.arange(4)
indices = np.zeros(4,dtype=np.int) # duplicate indices
a[indices] += x
a
= array([ 3., 0., 0., 0.])
More interesting stuff about duplicate indices in this question.
The first thing you need to realise is that a += x
doesn't map exactly to a.__iadd__(x)
, instead it maps to a = a.__iadd__(x)
. Notice that the documentation specifically says that in-place operators return their result, and this doesn't have to be self
(although in practice, it usually is). This means a[i] += x
trivially maps to:
a.__setitem__(i, a.__getitem__(i).__iadd__(x))
So, the addition technically happens in-place, but only on a temporary object. There is still potentially one less temporary object created than if it called __add__
, though.
这篇关于numpy的就地操作(例如,"+ =")如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!