Replacing NaNs in a Dataframe Column with Mean

Python

Uses the simple imputer in Sklearn to replace the NaNs in a dataframe column with the mean of the column.

 1|  from sklearn.impute import SimpleImputer
 2|  import numpy as np
 3|  
 4|  imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
 5|  imputer.fit(df[column_name])
 6|  df[column_name] = imputer.transform(df[columns_name]))
Did you find this snippet useful?

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