python - 使用多个逻辑条件从 numpy 数组中按列进行选择

标签 python arrays numpy

我可以使用myarray[myarray[:,1]==7]从第二个元素为7的numpy数组中选择行。如何扩展它以选择第二个元素为 7 或 9 的行?例如。类似 myarray[myarray[:,1]==7|==9] (显然这是行不通的)。

最佳答案

使用a[(a[:,1] == 7) | (a[:,1] == 9)] 例如:

In [6]: a = np.array([[4,7,8], [6,9,0], [4,4,4]])

In [7]: a[(a[:,1] == 7) | (a[:,1] == 9)]
Out[7]: 
array([[4, 7, 8],
       [6, 9, 0]])

另一种选择是使用numpy.logic_or

In [15]: a[np.logical_or(a[:, 1] == 7, a[:,1] == 9)]
Out[15]: 
array([[4, 7, 8],
       [6, 9, 0]])

关于python - 使用多个逻辑条件从 numpy 数组中按列进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147034/

相关文章:

Python:在多个列表中查找相同的项目

python - Twisted:WAITING子任务完成

c - 使用数组创建单链表时的警告

arrays - 为查询返回的每一行调用 set-returning plpgsql 函数

python - 从 python 字典创建 pandas 数据框

python - 保留满足两个或多个条件的 numpy 数组的值

Python - 在 CSV 之间复制列,但组合字符串/整数值复制为空白?

python - 如何使用python在文件中写入 'Ñ'

php - 使用 MySQL PHP 进行基于时间的 IP block

python - 替换 numPy 中二维数组中的一项特定项