Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print Row and Column Header if column/row is not NaN Pandas

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading