使用np.where在2D数组中查找匹配的行 [英] Using np.where to find matching row in 2D array

查看:59
本文介绍了使用np.where在2D数组中查找匹配的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将 np.where 与2D数组一起使用

I would like to know how I use np.where with 2D array

我有以下数组:

arr1 = np.array([[ 3.,  0.],
                 [ 3.,  1.],
                 [ 3.,  2.],
                 [ 3.,  3.],
                 [ 3.,  6.],
                 [ 3.,  5.]])

我想找到这个数组:

arr2 = np.array([3.,0.])

但是当我使用 np.where()时:

np.where(arr1 == arr2)

它返回:

(array([0, 0, 1, 2, 3, 4, 5]), array([0, 1, 0, 0, 0, 0, 0]))

我不明白这是什么意思.有人可以帮我解释一下吗?

I can't understand what it means. Can someone explain this for me?

推荐答案

您可能想要所有与 arr2 相等的行:

You probably wanted all rows that are equal to your arr2:

>>> np.where(np.all(arr1 == arr2, axis=1))
(array([0], dtype=int64),)

这意味着第一行(零索引)匹配.

Which means that the first row (zeroth index) matched.

您的方法存在的问题是numpy广播数组(通过

The problem with your approach is that numpy broadcasts the arrays (visualized with np.broadcast_arrays):

>>> arr1_tmp, arr2_tmp = np.broadcast_arrays(arr1, arr2)
>>> arr2_tmp
array([[ 3.,  0.],
       [ 3.,  0.],
       [ 3.,  0.],
       [ 3.,  0.],
       [ 3.,  0.],
       [ 3.,  0.]]) 

然后进行逐元素比较:

>>> arr1 == arr2
array([[ True,  True],
       [ True, False],
       [ True, False],
       [ True, False],
       [ True, False],
       [ True, False]], dtype=bool)

然后

np.where 会为您提供每个 True 的坐标:

and np.where then gives you the coordinates of every True:

>>> np.where(arr1 == arr2)
(array([0, 0, 1, 2, 3, 4, 5], dtype=int64),
 array([0, 1, 0, 0, 0, 0, 0], dtype=int64))
#       ^---- first match (0, 0)
#          ^--- second match (0, 1)
#             ^--- third match (1, 0)
#  ...

这意味着(0,0)(第一行的左边项目)是第一个 True ,然后是 0,1 (第一行的右边)项目,然后 1、0 (第二行,左侧项目),....

Which means (0, 0) (first row left item) is the first True, then 0, 1 (first row right item), then 1, 0 (second row, left item), ....

如果沿第一个轴使用 np.all ,则会得到所有完全相等的行:

If you use np.all along the first axis you get all rows that are completly equal:

>>> np.all(arr1 == arr2, axis=1)
array([ True, False, False, False, False, False], dtype=bool)

如果保持尺寸不变,则可以更好地可视化:

Can be better visualized if one keeps the dimensions:

>>> np.all(arr1 == arr2, axis=1, keepdims=True)
array([[ True],
       [False],
       [False],
       [False],
       [False],
       [False]], dtype=bool)

这篇关于使用np.where在2D数组中查找匹配的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆