0

我在 python 中有这个形状为 10,000x30 的矩阵。我想要的是找到行的索引,即从 10,000 行中,确定第 5 列值等于 0 的索引。

我怎样才能得到指数。获得索引后,我想从另一个矩阵 B 中选择相应的行。我该如何做到这一点?

4

1 回答 1

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类似的结果而不是使用逻辑索引 use np.where,它会返回一个数组元组,作为每个维度的索引:

>>> indices = np.where(a[:, 4] == 0)
>>> b[indices[0]]
array([[ 0.59533278,  0.15037691,  0.37865046,  0.99402371,  0.17325722]])
>>> 
于 2013-10-20T20:30:24.333 回答