Home > Blockchain >  How do I loop through a pandas dataframe, check to see if the data type of each column is a float nu
How do I loop through a pandas dataframe, check to see if the data type of each column is a float nu

Time:10-14

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.

CodePudding user response:

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)
  • Related