python - 检查不同 numpy 数组中的相同行

标签 python arrays numpy

如何在行式 true/false 数组的结果中获得两个数组之间的行式比较?

给定数据:

a = np.array([[1,0],[2,0],[3,1],[4,2]])
b = np.array([[1,0],[2,0],[4,2]])

结果第 1 步:

c = np.array([True, True,False,True])

最终结果:

a = a[c]

那么如何获取数组 c ????

P.S.: 在这个例子中,数组 ab 被排序,如果在你的解决方案中数组被排序很重要,请也提供信息

最佳答案

这是一个矢量化的解决方案:

res = (a[:, None] == b).all(-1).any(-1)

print(res)

array([ True,  True, False,  True])

请注意,a[:, None] == ba 的每一行与 b 元素进行比较。然后我们使用 all + any 来推断每个子数组是否有任何行都是 True:

print(a[:, None] == b)

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

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

 [[False False]
  [False False]
  [False False]]

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

关于python - 检查不同 numpy 数组中的相同行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352527/

相关文章:

arrays - 使用过滤器和排序在一起的 Google 表格

c - 在char数组中存储不同的数据类型

c++ - OpenGL 数组切换不起作用

python - 如何处理 numpy 中的 np.RankWarning?

python - 使用Python和Dask计算欧氏距离

python - 按行组合 Pandas 数据帧的有效方法

python - Seaborn.countplot : order categories by count

python - Matplotlib basemap 海岸坐标

python - 如何在 Python 中将多个文本填充行合并为一个?

python - 将 Python 列表转换为字典的简单方法