Home > Software design >  Numpy / Flatten a list
Numpy / Flatten a list

Time:06-30

I have create this of character

list1 = [['20']*3,['35']*2,['40']*4,['10']*2,['15']*3]

result :

[['20', '20', '20'], ['35', '35'], ['40', '40', '40', '40'], ['10', '10'], ['15', '15', '15']]

I can convert it into a single list using list comprehension

charlist = [x for sublist in list1 for x in sublist]
print(charlist)
['20', '20', '20', '35', '35', '40', '40', '40', '40', '10', '10', '15', '15', '15']

I was wondering how to do that with numpy

listNP=np.array(list1)

gives as output :

array([list(['20', '20', '20']), list(['35', '35']),
       list(['40', '40', '40', '40']), list(['10', '10']),
       list(['15', '15', '15'])], dtype=object)

The fact is that listNP.flatten() gives as an output the same result. Probably I missed a step when converting the list into an numpy array

CodePudding user response:

You can bypass all the extra operations and use np.repeat:

>>> np.repeat(['20', '35', '40', '10', '15'], [3, 2, 4, 2, 3])
array(['20', '20', '20', '35', '35', '40', '40', '40', '40',
       '10', '10', '15', '15', '15'], dtype='<U2')

If you need dtype=object, make the first argument into an array first:

arr1 = np.array(['20', '35', '40', '10', '15'], dtype=object)
np.repeat(arr1, [3, 2, 4, 2, 3])

CodePudding user response:

Use hstack()

import numpy as np
list1 = [['20']*3,['35']*2,['40']*4,['10']*2,['15']*3]
flatlist = np.hstack(list1)

print(flatlist)

['20' '20' '20' '35' '35' '40' '40' '40' '40' '10' '10' '15' '15' '15']

In trying to construct your ListNP with np.array as you do in the OP, I got a warning about jagged arrays and having to use dtype=object, but letting hstack construct it directly doesn't evoke a warning (thanks @Michael Delgado in the comments)

  • Related