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.
JavaScript
x
6
1
for col in WHO_df:
2
if WHO_df[col].dtype == 'float64':
3
WHO_df[col].fillna(WHO_df[col].mean())
4
else:
5
WHO_df[col].fillna(0)
6
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:
JavaScript
1
6
1
for col in WHO_df:
2
if WHO_df[col].dtype == 'float64':
3
WHO_df[col] = WHO_df[col].fillna(WHO_df[col].mean())
4
else:
5
WHO_df[col] = WHO_df[col].fillna(0)
6
or:
JavaScript
1
6
1
for col in WHO_df:
2
if WHO_df[col].dtype == 'float64':
3
WHO_df[col].fillna(WHO_df[col].mean(),inplace=True)
4
else:
5
WHO_df[col].fillna(0,inplace=True)
6