【问题标题】:Numpy:Getting rows of array where the corresponding array has a specific value results in IndexError: boolean index did not match indexed array along [duplicate]Numpy:获取对应数组具有特定值的数组行导致IndexError:布尔索引与[重复]中的索引数组不匹配
【发布时间】:2019-08-21 12:05:19
【问题描述】:

我试图在 stackoverflow 中找到一个回答这个问题的线程,但我找不到。因此,如果重复,请提供链接。
用例很常见:
我有两个数组:X 包含二维数据点,y 包含标签 0 或 1。
X 具有形状 (307, 2)
y 具有形状 (307, 1 )
我想拥有X 中的所有行,其中y 中的相应行的值为1。
我尝试了以下代码:
X[y==1]
但它会引发以下错误:

IndexError: boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1

我该怎么做?

【问题讨论】:

  • 你可以试试X[y, :]
  • @MadPhysicist 这给出了一个完全不同的数组 -> shape = (307, 1, 2)。这不是我要找的。只是y 中对应行的值为 1 -> shape = (9, 2) 的行
  • @MadPhysicist 而y 不是问题中描述的布尔值数组。因此,为了掩盖,您必须编写一个条件,然后导致IndexError 我也在问题中提到并找到了该问题的答案中所述的原因
  • X[y.ravel().astype(np.bool), :]

标签: python numpy


【解决方案1】:

我找到了以下方法:

X[np.where(np.any(y==1, axis=1))]

我也发现上面报错的原因是y有两个维度。下面的代码也可以工作,并且使用具有更好性能的掩码:

y = y.reshape(-1)
X[y==1,:]

【讨论】:

  • np.any(y==1, axis=1) 等价于y.ravel()。对where 的调用使这个花哨的索引,比只使用掩码效率低得多。
猜你喜欢
  • 2021-08-31
  • 2017-12-25
  • 2020-10-03
  • 2020-11-07
  • 2017-09-24
  • 2020-01-14
  • 2017-08-06
  • 2021-01-06
  • 1970-01-01
相关资源
最近更新 更多