python - 使用一维 bool 索引从二维数组中选择

标签 python arrays numpy

有时我会有一个ND我需要从中选择数据的数组,但数据标准只有 M < N方面。举个例子

## generate some matrix
test = np.arange(9).reshape((3, 3))
## some condition based on first-dimension only
selectMe = np.array([ True,  True, False], dtype=bool)

现在我想做

test[selectMe[:, None]]

但这会导致 IndexError:

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

当然,如果我在第二个维度上重复 bool 索引,一切都会正常 - 以下是预期的输出:

test[np.repeat(selectMe[:, None], 3, axis=1)]
Out[41]: array([0, 1, 2, 3, 4, 5])

但是,这是相当低效的。使用 numpy 实现这一目标的自然方法是什么?无需重复矩阵?

最佳答案

如果我理解您的问题,您可以使用省略号 (...) 来覆盖未过滤的维度:

import numpy as np

test = np.arange(10000).reshape((100, 100))

# condition
selectMe = np.random.randint(0, 2, 100).astype(bool)

assert (test[selectMe, ...].ravel() == test[np.repeat(selectMe[:, None], 100, axis=1)]).all()

%timeit test[selectMe, ...].ravel()                       # 11.6 µs
%timeit test[np.repeat(selectMe[:, None], 100, axis=1)]   # 103 µs

关于python - 使用一维 bool 索引从二维数组中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718603/

相关文章:

java - 不知道为什么JAVA数组会越界

python - 替换 numpy 数组列表中的值

python - 如何以编程方式将两个 aac 文件合并为一个文件?

python - 将列表映射到字典

python - iplot 奇怪的连接 Y 轴

python - 在python中使用public_key进行KeyCloak解码

c - c中的字符串数组声明

c++ - 如何在多维数组中组织文本文件中的数据并从中乘以列?

python - python中的映射求和

python - Pandas 中的递归定义