Fill NaNs With Values & By Series Using Pandas

Python

To fill NaNs with Pandas we can fill with a set value i.e. fill all NaN with zeros.

Alternatively, we can use a Series to fill the gaps. This works by using the value in the row index of the series to fill any corresponding NaNs in the row of the selected dataframe or dataframe column.

In the below examples, we fill df1 NaNs with zeros and fill NaNs in col_A of df2 with the corresponding values in col_B.

 1|  import pandas as pd
 2|  
 3|  # fill all NaN values with zeros
 4|  df1.fillna(0, inplace=True)
 5|  
 6|  # fill col_A NaNs with corresponding value in col_B
 7|  df2['col_A'] = df2['col_A'].fillna(df2['col_B'])
Did you find this snippet useful?

Sign up for free to to add this to your code library