Expand Numpy Matrix
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
Solution 1:
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)
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
.
Post a Comment for "Expand Numpy Matrix"