首页 > 解决方案 > 比较两个数组时出错:DeprecationWarning: elementwise comparison failed; 这将在未来引发错误

问题描述

我有一个a形状为的数组和形状为的(1000000,32)数组b(10000,32)

我想找到包含 b 行的 a 的索引。我写了以下代码:

I = np.argwhere((a == b[:, None]).all(axis=2))[:, 1]

当我在其他情况下对其进行测试时,它运行良好。但是对于我当前的数组,它给出了以下错误:

...\Anaconda3\lib\site-packages\ipykernel_launcher.py:111: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.

AttributeError: 'bool' object has no attribute 'all'

知道错误的根源是什么吗?谢谢

标签: pythonnumpyattributeerrornumpy-slicing

解决方案


跑:

result = (a[:, np.newaxis] == b).all(-1).any(-1)

脚步:

  • a[:, np.newaxis] == b- “按元素”比较。第一个和第二个索引 - 来自ab的行的索引,第三个索引 - 两行中的列索引。
  • ….all(-1)- a[i]在b[j]中是否有它的“对应物” (两行的所有 元素都相等)。
  • ….any(-1)- a[i]在b的任何行中都有它的“对应物”吗?

要检查每个步骤的结果,请使用 2 个数组,例如最多 10 行和 2 列。


推荐阅读