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

How to fill nan values in a column if the value from another column matches

Lets say i have a dataframe like this one:

      col1         col2     col3
0     data1         0        NaN
1     data1         0        NaN
2     data1         1        Done
3     data2         0        NaN
4     data2         1      To be done
5     data3         0        NaN
6     data3         1        Fail

How can i replace nan values in col3 for example: data1 in col1 hasa a row in col3 that is ‘Done’,
how can i pass this value to all NaN rows in col3 which contains data1 in col1?

Desirable df would look 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

      col1         col2      col3
0     data1         0        Done
1     data1         0        Done
2     data1         1        Done
3     data2         0      To be done
4     data2         1      To be done
5     data3         0        Fail
6     data3         1        Fail

>Solution :

Use groupby_bfill:

df['col3'] = df.groupby('col1')['col3'].bfill()
print(df)

# Output:
    col1  col2        col3
0  data1     0        Done
1  data1     0        Done
2  data1     1        Done
3  data2     0  To be done
4  data2     1  To be done
5  data3     0        Fail
6  data3     1        Fail
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