It’s a weird question – but can y’all think of a good way to just print the rows or a list of the rows and their corresponding column headers if the dataframe cell is not NaN?
Imagine a dataframe like this:
col1 col2 col3 col4
1 1 NaN 2 NaN
2 NaN NaN 1 2
3 2 NaN NaN 1
Result should look something like this:
1 [col1: 1, col3: 2]
2 [col3: 1, col4: 2]
3 [col1: 2, col4: 1]
Thanks in advance!
>Solution :
You can transpose the dataframe, and for each row, drop NaNs and convert to dict:
out = df.T.apply(lambda x: dict(x.dropna().astype(int)))
Output:
>>> out
1 {'col1': 1, 'col3': 2}
2 {'col3': 1, 'col4': 2}
3 {'col1': 2, 'col4': 1}
dtype: object