2D数组,检查哪些行与一个1D数组相等

huangapple go评论125阅读模式
英文:

2D array, check which rows are equal to a 1D array

问题

我有一个数组,N行和2列,

arr = np.arange(200, dtype=int).reshape(-1, 2)

而你知道arr[50][100, 101],但我不知道,所以我写了:

guess = np.array((100, 101), dtype=int)
arr == guess

期望得到一个由N个元素组成的一维布尔数组,但实际上我得到了一个由N行和2列组成的二维布尔数组。

是否有可能得到一个一维布尔数组,它逐个元素地将我的数组的行与猜测数组相等?顺便说一句,不要使用循环。

英文:

I have an array, N rows and 2 columns,

arr = np.arange(200, dtype=int).reshape(-1,2)

and you know that arr[50] is [100, 101], but I don't know that, so I write

guess = np.array((100, 101), dtype=int)
arr == guess

expecting a 1D boolean array with N elements, but instead I get a 2D boolean array, N rows and 2 columns.

Is it possible to have an 1D boolean array, that singles out the rows of my array that are equal, member by member, to the guess array? no loops, by the way.

答案1

得分: 1

你需要使用 all 来确保两列(全部列)都为 True:

(arr == guess).all(axis=1)

输出:

array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False,  True, False, False, False, # 这里是 50
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False])

注意:我已经将代码部分保留为英文。

英文:

You need to aggregate with all to ensure having True for both (all) columns:

(arr == guess).all(axis=1)

Output:

array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False,  True, False, False, False, # 50 is here
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False])

huangapple
  • 本文由 发表于 2023年3月7日 21:54:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定