You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Numpy矩阵中相似行归组排列?

问题描述

我构造了如下Numpy矩阵:

import numpy as np
I = np.eye(3)
I = np.concatenate([I] * 3)
print(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.]])

我需要将其整理为如下形式:

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()但没有效果。

解决方案

方法一:直接构造目标矩阵

利用np.repeat沿行方向重复单位矩阵的每一行,一步得到结果:

import numpy as np
target = np.repeat(np.eye(3), 3, axis=0)
print(target)

axis=0指定沿行维度重复,单位矩阵的每行都会被复制3次,直接生成目标格式。

方法二:基于现有矩阵重新排序

如果需要从已有的I矩阵调整顺序,可通过行特征排序:

# 获取每行中1所在的列索引
row_keys = np.argmax(I, axis=1)
# 根据索引排序原矩阵的行
target = I[np.argsort(row_keys)]
print(target)

np.argmax(I, axis=1)提取每行中1的位置(结果为[0,1,2,0,1,2,0,1,2]),np.argsort生成该序列的排序索引,用此索引取原矩阵行,即可将相同行聚合。

内容的提问来源于stack exchange,提问作者Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 01:35:11