Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening a list of lists, replacing empty sublists with a certain value

I have list of lists which contains a mix of empty and non-empty sublists. The total length of the list is 240.

_remain = [['24'],
 ['24'],
 ['17'],
 [],
 ['17'],
 [],
 ['17'],...]

And I've tried to flatten the list of lists into one list with:

[name for sublist in _remain for name in sublist]

But when I do this I get a list with length 220. The empty sublists are gone.

My desire is to get a flattened list, replacing empty lists with np.nan so that I can insert it into a pandas DataFrame.

The resultant list I would like to get:

['24',
 '24',
 'np.nan',
 '17',
 'np.nan',
 '17',...]

What should i try?

like image 564
Lumos Avatar asked Oct 31 '25 14:10

Lumos


2 Answers

You can do something like the following:

>>> [name for sublist in _remain for name in (sublist or [np.nan])]
['24', '17', nan, '17', nan, '17']
like image 183
CDJB Avatar answered Nov 02 '25 04:11

CDJB


Since pandas is tagged(though this can be done with vanilla python as suggested by the above answer), one way is:

pd.DataFrame(l).fillna(np.nan).squeeze().tolist()

['24', '17', nan, '17', nan, '17']
like image 44
anky Avatar answered Nov 02 '25 06:11

anky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!