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?
Question:
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.
Answers:
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)
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.
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)