基于条件在numpy/python中选择行

4
我生成了一个大小为4x4的正态分布随机矩阵,然后我必须选择行总和大于0的行。当我使用二维索引编写代码时,输出似乎不正确:
a = np.random.randn(4, 4)
a[a[:, 0] > 0]

我错过了什么?

请指定预期输出。 - Paul
行的总和大于0的行 - Andrewgorn
2个回答

3
a = np.random.randn(4, 4)
print(a)

在这种情况下,这将会得到:
[[-0.73576686 -0.34940161 -0.87025271 -0.61287421]
 [ 1.2738813  -0.3855836  -1.55570664  0.43841268]
 [-1.63614248  1.4127681   0.37276815 -0.35188628]
 [ 0.18570751 -0.31197874 -2.05487768 -0.05619158]]

然后应用条件:

a[np.sum(a, axis = 0)>0,:]

这里的结果为:

[[ 1.2738813 , -0.3855836 , -1.55570664,  0.43841268]]

编辑: 简单解释一下,np.sum(a, axis = 0)>0 创建了一个1D布尔掩码。然后我们使用索引切片将其应用于a的行,如 a[np.sum(a, axis = 0)>0,:]

1
尝试使用 np.wherenp.sum 结合使用:
import numpy as np

np.random.seed(0)
a = np.random.randn(4, 4)
indices = np.where(np.sum(a, axis=1) > 0)
print(a[indices])  # rows with sum > 0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接