在numpy数组中打印所有列都符合特定条件的行?

2024-10-02 12:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个500行5列的数组。我需要找到最后4列中每个列的值都大于100的所有行。我找到了一种方法来逐个检查每一列,但我希望能够同时检查所有列。我试着插入一个axis参数,但它给了我一个错误。一定有更简单的方法。这就是我可以得到的工作:

over1 = (array[:,1] >= 100)
over2 = (array[:,2] >= 100)
over3 = (array[:,3] >= 100)
over4 = (array[:,4] >= 100)
where = np.argwhere(over1&over2&over3&over4 == True)
there = array[where]
there2 = np.array(there[:,0]) 
#I had to reshape because the new array was a different shape for some reason

我是Python和Numpy的新手,所以遇到了一些麻烦


Tags: 方法true参数错误np数组wherearray
1条回答
网友
1楼 · 发布于 2024-10-02 12:26:21

我相信你在寻找:

x[(x[:, 1:] > 100).all(axis=1)]

考虑一下x

print(x)
array([[ 79, 192, 163,  94, 186],
       [111, 183, 152, 115, 171],
       [ 61, 125,  91, 163,  60],
       [110,  24,   0, 151, 180],
       [165, 111, 141,  19,  81]])

操作x[:, 1:] > 100在每个元素上广播该操作,从而生成布尔矩阵。你知道吗

print(x[:, 1:] > 100)
array([[ True,  True, False,  True],
       [ True,  True,  True,  True],
       [ True, False,  True, False],
       [False, False,  True,  True],
       [ True,  True, False, False]], dtype=bool)

np.all与内置函数all类似,如果每个元素都是True,则它的计算结果将是False。我们希望对每一行的每一列执行此检查,因此需要axis=1。你知道吗

mask = (x[:, 1:] > 100).all(1)
print(mask)
Out[362]: array([False,  True, False, False, False], dtype=bool)

遮罩现在将用于索引到原始。你知道吗

x[mask]
array([[111, 183, 152, 115, 171]])

相关问题 更多 >

    热门问题