If you want to enter missing values with mode in some dataframe df columns, you can simply fillna Series , created by selecting at the iloc position:
cols = ["workclass", "native-country"] df[cols]=df[cols].fillna(df.mode().iloc[0])
Or:
df[cols]=df[cols].fillna(mode.iloc[0])
Your choice:
df[cols]=df.filter(cols).fillna(mode.iloc[0])
Example:
df = pd.DataFrame({'workclass':['Private','Private',np.nan, 'another', np.nan], 'native-country':['United-States',np.nan,'Canada',np.nan,'United-States'], 'col':[2,3,7,8,9]}) print (df) col native-country workclass 0 2 United-States Private 1 3 NaN Private 2 7 Canada NaN 3 8 NaN another 4 9 United-States NaN mode = df.filter(["workclass", "native-country"]).mode() print (mode) workclass native-country 0 Private United-States cols = ["workclass", "native-country"] df[cols]=df[cols].fillna(df.mode().iloc[0]) print (df) col native-country workclass 0 2 United-States Private 1 3 United-States Private 2 7 Canada Private 3 8 United-States another 4 9 United-States Private
source share