简体   繁体   English

如何正确比较3个不同的numpy数组的元素?

[英]How to correctly compare elements of 3 different numpy arrays?

I'm trying to compare elements at the same index from 3 different arrays. 我正在尝试比较3个不同数组中处于相同索引的元素。 When I try if arr1[i] == arr2[i] I get the The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 当我尝试if arr1[i] == arr2[i]我得到了The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() . The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Here's the whole function: 这是整个功能:

def tmr(arr1, arr2, arr3):
arr4 = arr1
for i in range(arr4.size):
    if arr1[i] == arr2[i]:
        arr4[i] = arr1[i]
    else:
        if arr2[i] == arr3[i]:
            arr4[i] = arr3[i]
return arr4

I'm more familiar with C++ than Python and I really can't see why this doesn't exactly work. 我对C ++的了解比对Python的了解还多,我真的不明白为什么这不能完全起作用。 I also tried using zip like this: 我也尝试使用zip这样的方式:

for w, x, y, z in zip(arr4, arr1, arr2, arr3):
    if x == y == z:
        w = x

Interpreting this as for the intended result in your last example using zip , try: 使用zip解释上一次示例中的预期结果,请尝试:

arr4 = arr1[np.equal(arr1, arr2) & np.equal(arr2, arr3)]

For the interpretation in your first code block you can use list comprehension: 对于第一个代码块中的解释,可以使用列表理解:

list4 = [arr1[i] if arr1[i] == arr2[i] else arr3[i] if arr2[i] == arr3[i] else None for i in range(len(arr1))]
arr4 = np.array(list4)

Based on your example I'm not sure the default values for arr4 if neither arr1[i] == arr2[i] nor arr2[i] == arr3[i] , so have left them as None above. 根据您的示例,如果arr1[i] == arr2[i]arr2[i] == arr3[i]None ,我不确定arr4的默认值,因此在上面将它们保留为None

The two approaches provide different answers, but if I'm interpreting correctly, the first is the desired behaviour. 两种方法提供了不同的答案,但是如果我的解释正确,第一种就是所需的行为。

numpy array functions np.equal , np.logical_and , np.where - vectorized/broadcasting numpy数组函数np.equalnp.logical_andnp.where矢量化/广播

import numpy as np
arr1 = np.array([0,1,2,3,7])
arr2 = np.array([0,1,0,2,7])
arr3 = np.array([0,0,2,1,7])

arr4 = np.ones(5)*10


eq_idx = np.where(np.logical_and(np.equal(arr1, arr3), np.equal(arr2, arr3)))

arr4[eq_idx] = arr1[eq_idx]

arr4
Out[28]: array([ 0., 10., 10., 10.,  7.])

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

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