展开numpy矩阵 [英] Expand numpy matrix
问题描述
我正在尝试以某种方式扩展numpy矩阵,通常如下所示:
I am trying to somehow expand numpy matrices, which typically look like:
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)
最后一列包含生成的矩阵的实例数,然后应如下所示:
The last column contains number of instances of the resulting matrix, which then should look like this:
# 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)
所以,第一行三遍,第二行两遍,等等.
So, three times 1st row, two times 2nd etc.
我想知道最快和/或最优雅的python-way是什么吗?
I wonder what would be the fastest and/or the most elegant python-way?
许多tnx!下午
推荐答案
您可以使用 np.repeat
重复每行mtx[:,:2]
的前两列,由第三列arr[:,2]
的相应行给出的次数:
You could use np.repeat
to repeat the first two columns of each row mtx[:,:2]
the number of times given by the corresponding row of the third column 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
对象.
The third column needs to be cast to integer values first (e.g. using astype(int)
). I also found it necessary to treat mtx
as an array
for this to work: you can easily turn it back into a matrix
object again with np.matrix
.
这篇关于展开numpy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!