如果最小值满足条件,则获取 2D np.array 中每一行的最小值的索引
Get the indices of min values for each row in a 2D np.array, if the min value satisfies a condition
我有一个二维 np.array
,尺寸为 1000 (rows) x 12 (columns)
。
我需要获取低于 1.5
.
的那些值的索引
如果一行包含多个满足此条件的值,那么我只需要保留最低的索引。
我很乐意使用
idx1,idx2=np.where(x < 1.5)
,
但这有时 returns 同一行中的几个索引。
我当然可以遍历 idx1
中所有重复的行,只保留 x
中值最低的索引,但我想知道是否有更 pythonic 的方式。
谢谢
一种方法是使用 numpy masked array。让我们定义以下随机 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]])
我们可以定义一个掩码数组:
ma = np.ma.array(a, mask = a >= 1.5)
print(ma.round(2))
[[1.41 -0.68]
[-1.53 --]
[1.19 --]
[-- 1.26]]
为了处理没有值低于阈值的行,您可以这样做:
m = ma.mask.any(axis=1)
# array([ True, True, True, True])
如果给定行中没有有效值,它将包含 False
。
然后在掩码数组上取 np.argmin
以获得最小值低于 1.5 的列:
np.argmin(ma, axis=1)[m]
# array([1, 0, 0, 1])
对于你可以做的行:
np.flatnonzero(m)
# array([0, 1, 2, 3])
你可以这样做:
# 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]
我有一个二维 np.array
,尺寸为 1000 (rows) x 12 (columns)
。
我需要获取低于 1.5
.
的那些值的索引
如果一行包含多个满足此条件的值,那么我只需要保留最低的索引。
我很乐意使用
idx1,idx2=np.where(x < 1.5)
,
但这有时 returns 同一行中的几个索引。
我当然可以遍历 idx1
中所有重复的行,只保留 x
中值最低的索引,但我想知道是否有更 pythonic 的方式。
谢谢
一种方法是使用 numpy masked array。让我们定义以下随机 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]])
我们可以定义一个掩码数组:
ma = np.ma.array(a, mask = a >= 1.5)
print(ma.round(2))
[[1.41 -0.68]
[-1.53 --]
[1.19 --]
[-- 1.26]]
为了处理没有值低于阈值的行,您可以这样做:
m = ma.mask.any(axis=1)
# array([ True, True, True, True])
如果给定行中没有有效值,它将包含 False
。
然后在掩码数组上取 np.argmin
以获得最小值低于 1.5 的列:
np.argmin(ma, axis=1)[m]
# array([1, 0, 0, 1])
对于你可以做的行:
np.flatnonzero(m)
# array([0, 1, 2, 3])
你可以这样做:
# 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]