Skip to content
Advertisement

Python Pandas replace NaN in one column with value from corresponding row of second column

I am working with this Pandas DataFrame in Python.

JavaScript

I need to replace all NaNs in the Temp_Rating column with the value from the Farheit column.

This is what I need:

JavaScript

If I do a Boolean selection, I can pick out only one of these columns at a time. The problem is if I then try to join them, I am not able to do this while preserving the correct order.

How can I only find Temp_Rating rows with the NaNs and replace them with the value in the same row of the Farheit column?

Advertisement

Answer

Assuming your DataFrame is in df:

JavaScript

First replace any NaN values with the corresponding value of df.Farheit. Delete the 'Farheit' column. Then rename the columns. Here’s the resulting DataFrame:

resulting DataFrame

Advertisement