简体   繁体   English

比较numpy数组中的多个值

[英]Compare multiple values in numpy array

I have a numpy array 我有一个numpy数组

a = numpy.array([1,2,3,0])

I would like to do something like 我想做点什么

a == numpy.array([0,1,2,3])

and get 得到

[[False, True,   False, False],
 [False, False,  True,  False],
 [False, False,  False, True ],
 [True,  False,  False, False]]

In other words, I want the ith column to show whether each element of a is equal to i. 换句话说,我希望第i列显示a每个元素是否等于i。 This feels like the kind of thing that numpy might make easy. 这感觉就像numpy可能变得容易的东西。 Any ideas? 有任何想法吗?

The key concept to use here is broadcasting. 这里使用的关键概念是广播。

a = numpy.array([1,2,3,0])
b = numpy.array([0,1,2,3])
a[..., None] == b[None, ...]

The result: 结果:

>>> a[..., None] == b[None, ...]
array([[False,  True, False, False],
       [False, False,  True, False],
       [False, False, False,  True],
       [ True, False, False, False]], dtype=bool)

Understanding how to use broadcasting will greatly improve your NumPy code. 了解如何使用广播将大大改善您的NumPy代码。 You can read about it here: 你可以在这里读到它:

You can reshape to vector and covector and compare: 你可以重塑矢量和矢量并比较:

>>> a = numpy.array([1,2,3,0])
>>> b = numpy.array([0,1,2,3])
>>> a.reshape(-1,1) == b.reshape(1,-1)
array([[False,  True, False, False],
       [False, False,  True, False],
       [False, False, False,  True],
       [ True, False, False, False]], dtype=bool)

The above is one way of doing it. 以上是这样做的一种方式。 Another possible way (though I'm still not convinced there isn't a better way) is: 另一种可能的方式(虽然我仍然不相信没有更好的方法)是:

import numpy as np
a = np.array([[1, 2, 3, 0]]).T
b = np.array([[0, 1, 2, 3]])
a == b
array([[False,  True, False, False],
   [False, False,  True, False],
   [False, False, False,  True],
   [ True, False, False, False]], dtype=bool)

I think you just need to make sure one is a column vector and one is a row vector and it will do comparison for you. 我想你只需要确保一个是列向量,一个是行向量,它会为你做比较。

You can use a list comprehension to iterate through each index of a and compare that value to b : 您可以使用列表推导来遍历a每个索引并将该值与b进行比较:

>>> import numpy as np
>>> a = np.array([1,2,3,0])
>>> b = np.array([0,1,2,3])
>>> ans = [ list(a[i] == b) for i in range(len(a)) ]
>>> ans
[[False,  True, False, False],
 [False, False,  True, False],
 [False, False, False,  True],
 [ True, False, False, False]]

I made the output match your example by creating a list of lists, but you could just as easily make your answer a Numpy array. 我通过创建列表列表使输出与您的示例匹配,但您可以轻松地使您的答案成为Numpy数组。

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

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