Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Repeat Array while Maintaining Order within group

I have the below array and would like to repeat each array n times.

x_array

[array([14.91488012,  1.2986064 ,  4.98965322]),
 array([2.39389187e+02, 1.04442059e-01, 3.06391338e-01]),
 array([ 48.19437348, 201.09951372,   0.35223001]),
 array([ 19.96978171, 367.52578786,   0.68676553]),
 array([0.55120466, 0.27133609, 0.75646697]),
 array([8.21287360e+02, 1.76495077e+02, 4.87263691e-01]),
 array([184.03439377,   1.24823107,   5.33109884]),
 array([575.59800297, 186.4650814 ,   2.21028258]),
 array([0.50308552, 3.09976082, 0.10537899]),
 array([1.02259912e+00, 1.52282513e+02, 1.15085308e-01])]

I’ve tried np.repeat(x_array, 2) but this doesn’t preserve the order of the matrix/array. I’ve also tried x_array*2, but this seems to just put the new array at the bottom. I was hopping to repeat x_array[0] n times and do the same for the next set of arrays, so that I have n total of each in order.

Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to specify the axis:

>>> np.repeat(x_array, 2, axis=0)
array([[1.49149e+01, 1.29861e+00, 4.98965e+00],
       [1.49149e+01, 1.29861e+00, 4.98965e+00],
       [2.39389e+02, 1.04442e-01, 3.06391e-01],
       [2.39389e+02, 1.04442e-01, 3.06391e-01],
       ...,
       [5.03086e-01, 3.09976e+00, 1.05379e-01],
       [5.03086e-01, 3.09976e+00, 1.05379e-01],
       [1.02260e+00, 1.52283e+02, 1.15085e-01],
       [1.02260e+00, 1.52283e+02, 1.15085e-01]])

From the docs:

numpy.repeat(a, repeats, axis=None)

axis int, optional
The axis along which to repeat values. By default, use the flattened input array, and return a flat output array.

(added bold)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading