将numpy matrix中相似的行放在一起

xfb7svmp  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(89)

我有一个这样的矩阵:

I = np.eye(3)
I = np.concatenate([I] * 3)
I

array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.],
       [1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.],
       [1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

而且我需要像below一样组织矩阵,我怎么能在numpy中做到呢?

array([[1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [0., 1., 0.],
       [0., 1., 0.],
       [0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 1.],
       [0., 0., 1.]])

我尝试使用np.sort(),但它没有工作。

c8ib6hqw

c8ib6hqw1#

numpy.sort将独立地对列进行排序,您需要使用numpy.lexsort并使用输出对行进行重新排序:

out = I[np.lexsort(I.T)]

输出:

array([[1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [0., 1., 0.],
       [0., 1., 0.],
       [0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 1.],
       [0., 0., 1.]])

您也可以合并numpy.uniquenumpy.repeat

idx, num = np.unique(I, axis=0, return_counts=True)

out = np.repeat(idx, num, axis=0)

输出:

array([[0., 0., 1.],
       [0., 0., 1.],
       [0., 0., 1.],
       [0., 1., 0.],
       [0., 1., 0.],
       [0., 1., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.]])

相关问题