[英]Print rows where all columns meet a certain criteria in a numpy array?
I have an array with 500 rows and 5 columns.我有一个包含 500 行和 5 列的数组。 I need to find all the rows where the value in each of the last 4 columns is greater than 100. I found a way to check each column individually but I'd like to be able to check them all at once.我需要找到最后 4 列中每一列的值都大于 100 的所有行。我找到了一种单独检查每一列的方法,但我希望能够一次检查它们。 I tried inserting an axis argument but it gives me an error.我尝试插入一个轴参数,但它给了我一个错误。 There must be a simpler way to do this.必须有一种更简单的方法来做到这一点。 This is what I could get to work:这是我可以开始工作的:
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
I'm new to Python and Numpy so I'm having some trouble我是 Python 和 Numpy 的新手,所以遇到了一些麻烦
I believe you're looking for:我相信你正在寻找:
x[(x[:, 1:] > 100).all(axis=1)]
Consider x
:考虑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]])
The operation x[:, 1:] > 100
broadcasts the operation on every element, resulting in a boolean matrix.操作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
, similar to the inbuilt function all
, will evaluate to True
if every element is True
, else it evaluates to False
. np.all
,类似于内置功能all
将评估为True
,如果每一个元素是True
,否则结果为False
。 We want to perform this check every column per row, so we need axis=1
.我们希望对每一行的每一列执行此检查,因此我们需要axis=1
。
mask = (x[:, 1:] > 100).all(1)
print(mask)
Out[362]: array([False, True, False, False, False], dtype=bool)
The mask will now be used to index into the original.现在将使用掩码来索引原始文件。
x[mask]
array([[111, 183, 152, 115, 171]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.