Skip to content
Advertisement

How do I loop through a pandas dataframe, check to see if the data type of each column is a float number, then replace null values with mean?

I am trying to iterate through a pandas Dataframe which has columns with different data types, and replace them with different data types based on their null values.

for col in WHO_df:
    if WHO_df[col].dtype == 'float64':
        WHO_df[col].fillna(WHO_df[col].mean())
    else:
        WHO_df[col].fillna(0)

This code did not work as the null values are not replaced in the dataframe.

Advertisement

Answer

fillna() doesn’t normaly edit your dataframe. you have 2 ways:

for col in WHO_df:
if WHO_df[col].dtype == 'float64':
    WHO_df[col] = WHO_df[col].fillna(WHO_df[col].mean())
else:
    WHO_df[col] = WHO_df[col].fillna(0)

or:

for col in WHO_df:
if WHO_df[col].dtype == 'float64':
    WHO_df[col].fillna(WHO_df[col].mean(),inplace=True)
else:
    WHO_df[col].fillna(0,inplace=True)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement