Python 展开numpy矩阵

Python 展开numpy矩阵,python,numpy,matrix,Python,Numpy,Matrix,我试图以某种方式扩展numpy矩阵,它通常看起来像: import numpy as np mtx = np.matrix([[['a','b','c'], ['x'], 3], [['d','e','f'], ['y'], 2], [['g','h','i'], ['z'], 1]]) mtx # matrix([[['a', 'b', 'c'], ['x'], 3], # [['d', 'e', 'f'], ['y'], 2], # [['g', '

我试图以某种方式扩展numpy矩阵,它通常看起来像:

import numpy as np

mtx = np.matrix([[['a','b','c'], ['x'], 3], [['d','e','f'], ['y'], 2],
    [['g','h','i'], ['z'], 1]])
mtx
# matrix([[['a', 'b', 'c'], ['x'], 3],
#         [['d', 'e', 'f'], ['y'], 2],
#         [['g', 'h', 'i'], ['z'], 1]], dtype=object)
最后一列包含结果矩阵的实例数,其应如下所示:

# matrix([[['a', 'b', 'c'], ['x']],
#         [['a', 'b', 'c'], ['x']],
#         [['a', 'b', 'c'], ['x']],
#         [['d', 'e', 'f'], ['y']],
#         [['d', 'e', 'f'], ['y']],
#         [['g', 'h', 'i'], ['z']]], dtype=object)
所以,三次第一排,两次第二排等等

我想知道最快和/或最优雅的python方式是什么

很多tnx!PM

您可以使用重复每行的前两列
mtx[:,:2]
第三列的相应行所给出的次数
arr[:,2]

>>> arr = np.asarray(mtx)
>>> np.repeat(arr[:,:2], arr[:,2].astype(int), axis=0)
array([[['a', 'b', 'c'], ['x']],
       [['a', 'b', 'c'], ['x']],
       [['a', 'b', 'c'], ['x']],
       [['d', 'e', 'f'], ['y']],
       [['d', 'e', 'f'], ['y']],
       [['g', 'h', 'i'], ['z']]], dtype=object)
第三列需要首先转换为整数值(例如,使用
astype(int)
)。我还发现有必要将
mtx
视为一个
array
,这样才能工作:您可以使用
np.matrix
轻松地将其重新转换为
matrix
对象