我有两个数组一个Int,一个是位
s = [ [1] x = [ [1 0 0 0 0]
[4] [1 1 1 1 0]
[9] [0 1 1 1 0]
[0] [0 0 1 0 0]
[3] ] [0 1 1 0 0]]
我想找到s中最小的两个元素(随机给定)然后(选择并打印)基于s数组的x(随机给定)两行, 例如,s [i]中的最小元素是s [3] = 0,s [0] = 1,所以我想选择x [3] [0 0 1 0 0]和x [0] [1 0 0 0 0]
import numpy as np
np.set_printoptions(threshold=np.nan)
s= np.random.randint(5, size=(5))
x= np.random.randint (2, size=(5, 5))
print (s)
print (x)
我尽力使用“for loop”但没有运气,任何建议都将受到赞赏。
答案 0 :(得分:1)
您可以使用numpy.argpartition查找s
中两个最小元素的索引,并将其用作子集x
的行索引:
s
# array([3, 0, 0, 1, 2])
x
# array([[1, 0, 0, 0, 1],
# [1, 0, 1, 1, 1],
# [0, 0, 1, 0, 0],
# [1, 0, 0, 1, 1],
# [0, 0, 1, 0, 1]])
x[s.argpartition(2)[:2], :]
# array([[1, 0, 1, 1, 1],
# [0, 0, 1, 0, 0]])