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

Numpy create array from list of integers specifying the array elements

Say we have the list a = [3,4,2,1], from a we want to obtain the following array: b = [0,0,0,1,1,1,1,2,2,3].

I have managed to do it like this:

import numpy as np 
a = [3,4,2,1]
b = np.concatenate([[i] * n for i, n in enumerate(a])
print(b)

Output:

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

array([0, 0, 0, 1, 1, 1, 1, 2, 2, 3])

Which works fine, but I can’t help but wonder if there is a better way?

>Solution :

Try np.repeat: np.repeat([0,1,2,3], [3,4,2,1])

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