Extract list for each row in panda dataframe while removing nans

Viewed 34

Quite similar to the question here

Having a dataframe

                 COL_A    ...    COL G   ...      COL N
0                 NaN  ...        Nan    ...        wds
1                 NaN  ...        Nan    ...        dst
2                 ds  ...         Nan    ...        NaN
3                 NaN  ...        Nan    ...        NaN

I would like to extract list of lists (or numpy array , dont mind) as following:

l = [['wds'],['dst],['dst'] , [] ] ,i.e

len(l) == df.shape[0]

When trying things like :

df.stack().groupby(level=0).apply(list).tolist()
Out[]: [['wds'],['dst'],['dst']]

The all-nan rows are being removed.

1 Answers

Use DataFrame.agg with Series.dropna:

L = df.agg(lambda x: x.dropna().tolist(), axis=1).tolist()
print (L)
[['wds'], ['dst'], ['ds'], []]
Related