我在python中有这个10,000x30形状的矩阵。我想要的是找到行的索引,即从10,000行中,确定第5列值等于0的索引。
我如何获得指数。一旦我得到索引,我想从另一个矩阵B中选择相应的行。我该如何做到这一点?
答案 0 :(得分:0)
>>> a = np.random.randint(0, 10, (10, 5))
>>> a
array([[4, 9, 7, 2, 9],
[1, 9, 5, 0, 8],
[1, 7, 7, 8, 4],
[6, 2, 1, 9, 6],
[6, 2, 0, 0, 8],
[5, 5, 8, 4, 5],
[6, 8, 8, 8, 8],
[2, 2, 3, 4, 3],
[3, 6, 2, 1, 2],
[6, 3, 2, 4, 0]])
>>> a[:, 4] == 0
array([False, False, False, False, False, False, False, False, False, True], dtype=bool)
>>> b = np.random.rand(10, 5)
>>> b
array([[ 0.37363295, 0.96763033, 0.72892652, 0.77217485, 0.86549555],
[ 0.83041897, 0.35277681, 0.13011611, 0.82887195, 0.87522863],
[ 0.88325189, 0.67976957, 0.56058782, 0.58438597, 0.10571746],
[ 0.27305838, 0.72306733, 0.01630463, 0.86069002, 0.9458257 ],
[ 0.23113894, 0.30396521, 0.92840314, 0.39544522, 0.59708927],
[ 0.71878406, 0.91327744, 0.71407427, 0.65388644, 0.416599 ],
[ 0.83550209, 0.85024774, 0.96788451, 0.72253464, 0.41661953],
[ 0.61458993, 0.34527785, 0.20301719, 0.10626226, 0.00773484],
[ 0.87275531, 0.54878131, 0.24933454, 0.29894835, 0.66966912],
[ 0.59533278, 0.15037691, 0.37865046, 0.99402371, 0.17325722]])
>>> b[a[:,4] == 0]
array([[ 0.59533278, 0.15037691, 0.37865046, 0.99402371, 0.17325722]])
>>>
要获得find
之类的结果而不是使用逻辑索引,请使用np.where
,它返回一个数组元组,作为每个维度的索引:
>>> indices = np.where(a[:, 4] == 0)
>>> b[indices[0]]
array([[ 0.59533278, 0.15037691, 0.37865046, 0.99402371, 0.17325722]])
>>>