Reputation: 337
I have this operation of filling missing values.
mean_impute = df['column'].fillna(value=df['column'].mean())
median_impute = df['column'].fillna(value=df['column'].median())
mode_impute = df['column'].fillna(value=df['column'].mode())
Is there any way on how to replicate this line of code in a much cleaner way, is there a way to loop
on this or to create a function
?
Upvotes: 0
Views: 65
Reputation: 12731
This might not be best practice (because of eval
) but you could avoid to repeat yourself by storing your results in a dictionary:
impute = dict()
for fun in ["mean", "median", "mode"]:
impute[fun] = eval(f"df['column'].fillna(value=df['column'].{fun}())")
Upvotes: 1