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?
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With