python - 如何选择满足条件的行

标签 python arrays numpy scipy extract

考虑三个 numpy 数组:

x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 
y = np.array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
z = np.array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])

如何从 x 生成数组,其中满足涉及 yz 的条件。 例如 "extract x where y+z = 2" 会返回:

np.array([3, 7])

(因为我有很多数据,我希望它尽可能快)

最佳答案

>>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> y = np.array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
>>> z = np.array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])

>>> y + z == 2
array([False, False, False,  True, False, False, False,  True, False, False], dtype=bool)

# here y+z==2 returns a boolean array that can be used to index x
>>> x[y + z == 2]
array([3, 7])

关于python - 如何选择满足条件的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23184685/

相关文章:

python - 使用 django 和 JWT 在 N 分钟后重新登录

php - 将数据从 1 个数组添加到另一个

python - 如何在 Python 中求解非线性方程组?

python - 为什么 numpy.matrix 的 numpy.copy 的行为与原始矩阵不同?与该副本转置的乘法不起作用

python - 按一列分组并计算 Pandas 中的多个类别

python - 获取新的唯一列表,仅包含原始列表中最后出现的元素

python - 我的简单 python 脚本出错

arrays - Ruby:插入和排序数字

arrays - 将 ls 输出转换为数组

python - cv2中的人脸检测错误