[英]Correct usage of numpy.nditer?
I'm trying to do an array operation with numpy.nditer , but don't get the expected result. 我正在尝试使用numpy.nditer进行数组操作,但是没有得到预期的结果。
My code is 我的代码是
import numpy as np
arr1 = - np.random.random((2,2))
arr2 = np.random.random((2,2))
arr = np.zeros((2,2))
it = np.nditer([arr1, arr2, arr], [], [['readonly'], ['readonly'], ['writeonly']])
for a1, a2, a in it:
a = a1 if -a1 < a2 else a2
print arr
print it.operands[2]
I'm getting all zero results in both arr
and it.operands[2]
, but I expected values from either arr1
or arr2
. 我在
arr
和it.operands[2]
得到全部零结果,但我期望来自arr1
或arr2
值。 What would be the correct way to assign values to arr
in the iteration? 在迭代中为
arr
赋值的正确方法是什么?
Doing a =
in Python will simply rebind the local variable a
; 在Python中执行
a =
将简单地重新绑定局部变量a
; it won't affect what a
contains. 也不会影响什么
a
包含。
With nditer
, the iteration variables a1
, a2
and a
are actually 0-d arrays. 对于
nditer
,迭代变量a1
, a2
和a
实际上是0-d数组。 Thus, to change a
, use the (slightly odd) a[()] =
syntax: 因此,要更改
a
,请使用(略微奇怪的) a[()] =
语法:
for a1, a2, a in it:
a[()] = a1 if -a1 < a2 else a2
Note, though, that your whole code can be simplified greatly by using np.where
: 但请注意,使用
np.where
可以大大简化整个代码:
import numpy as np
arr1 = - np.random.random((2,2))
arr2 = np.random.random((2,2))
arr = np.where(-arr1 < arr2, arr1, arr2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.