简体   繁体   English

正确使用numpy.nditer?

[英]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 . 我在arrit.operands[2]得到全部零结果,但我期望来自arr1arr2值。 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 ,迭代变量a1a2a实际上是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.

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