[英]Get the indices of min values for each row in a 2D np.array, if the min value satisfies a condition
I've a 2D np.array
with dimension 1000 (rows) x 12 (columns)
. 我有一个二维
np.array
,尺寸为1000 (rows) x 12 (columns)
。
I need to get the indices of those values that are below 1.5
. 我需要获取低于
1.5
的那些值的索引。
If a row contains more than one value that satisfies this condition, then I need to keep only the indices of the lowest. 如果一行包含多个满足此条件的值,那么我只需要保留最低的索引。
I'd be quite happy with using idx1,idx2=np.where(x < 1.5)
, but this sometimes returns several indices that are in the same rows. 我对使用
idx1,idx2=np.where(x < 1.5)
很满意,但这有时会返回同一行中的多个索引。 I could of course loop over all repeated rows in idx1
and keep only the indices whose values in x
where are the lowest, but I was wondering if there's a more pythonic way. 我当然可以循环遍历
idx1
所有重复的行,并只保留x
中的值最低的索引,但是我想知道是否还有更多的Python方式。
Thanks 谢谢
One way would be to use a numpy masked array . 一种方法是使用numpy掩码数组 。 Lets define the following random
ndarray
: 让我们定义以下随机
ndarray
:
a = np.random.normal(1,2,(4,2))
print(a.round(2))
array([[ 1.41, -0.68],
[-1.53, 2.74],
[ 1.19, 2.66],
[ 2. , 1.26]])
We can define a masked array with: 我们可以使用以下方法定义蒙版数组:
ma = np.ma.array(a, mask = a >= 1.5)
print(ma.round(2))
[[1.41 -0.68]
[-1.53 --]
[1.19 --]
[-- 1.26]]
In order to deal with rows with no values bellow the threshold, you could do: 为了处理阈值以下没有值的行,您可以执行以下操作:
m = ma.mask.any(axis=1)
# array([ True, True, True, True])
Which will contain a False
if there are no valid values along a given row. 如果给定行上没有有效值,则它将包含
False
。 And then take the np.argmin
over the masked array to get the columns with the minimum values bellow 1.5: 然后将
np.argmin
放在被屏蔽的数组上,以获取最小值在1.5以下的列:
np.argmin(ma, axis=1)[m]
# array([1, 0, 0, 1])
And for the rows you could do: 对于行,您可以执行以下操作:
np.flatnonzero(m)
# array([0, 1, 2, 3])
You can just do this: 您可以这样做:
# First index is all rows
idx1 = np.arange(len(x))
# Second index is minimum values
idx2 = np.argmin(m, axis=1)
# Filter rows where minimum is not below threshold
valid = x[idx1, idx2] < 1.5
idx1 = idx1[valid]
idx2 = idx2[valid]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.