从 numpy ndarray 索引多个最小值
indexing multiple minimum values from a numpy ndarray
我在下面的数据结构中有一组坐标。
如何找到 K 个最小 X 值点的索引?
例如对于下面带有 k=3
的数据,输出应该类似于 [5,4,3]
array([[[463, 445]],
[[461, 447]],
[[461, 448]],
[[ 42, 2]],
[[ 41, 1]],
[[ 40, 100]]], dtype=int32)
由于你的数据不是nx2
的形状,先reshape然后用argsort
先得到排序后的索引和索引k
x = np.array(
[[[463, 445]],
[[461, 447]],
[[461, 448]],
[[ 42, 2]],
[[ 41, 1]],
[[ 40, 100]]])
k = 3
print (np.argsort(x.reshape(-1,2), axis=0)[:k][:,0])
输出:
[5 4 3]
x.reshape(-1,2)
: 重塑为 n X 2
np.argsort(x.reshape(-1,2), axis=0)
:按列排序;所以 x's
和 y's
都是独立排序的
np.argsort(x.reshape(-1,2), axis=0)[:k]
:获取top k idx
np.argsort(x.reshape(-1,2), axis=0)[:k][:,0]
:得到x的idx
要在 y's
上做同样的事情,您需要做的是索引 idx of y
s` 即。
print (np.argsort(x.reshape(-1,2), axis=0)[:k][:,1])
输出:
array([5, 4, 3])
我在下面的数据结构中有一组坐标。
如何找到 K 个最小 X 值点的索引?
例如对于下面带有 k=3
的数据,输出应该类似于 [5,4,3]
array([[[463, 445]],
[[461, 447]],
[[461, 448]],
[[ 42, 2]],
[[ 41, 1]],
[[ 40, 100]]], dtype=int32)
由于你的数据不是nx2
的形状,先reshape然后用argsort
先得到排序后的索引和索引k
x = np.array(
[[[463, 445]],
[[461, 447]],
[[461, 448]],
[[ 42, 2]],
[[ 41, 1]],
[[ 40, 100]]])
k = 3
print (np.argsort(x.reshape(-1,2), axis=0)[:k][:,0])
输出:
[5 4 3]
x.reshape(-1,2)
: 重塑为n X 2
np.argsort(x.reshape(-1,2), axis=0)
:按列排序;所以x's
和y's
都是独立排序的np.argsort(x.reshape(-1,2), axis=0)[:k]
:获取top k idxnp.argsort(x.reshape(-1,2), axis=0)[:k][:,0]
:得到x的idx
要在 y's
上做同样的事情,您需要做的是索引 idx of y
s` 即。
print (np.argsort(x.reshape(-1,2), axis=0)[:k][:,1])
输出:
array([5, 4, 3])