Armando Bridena
Armando Bridena

Reputation: 337

How to consolidate different methods in Python

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

Answers (1)

Tranbi
Tranbi

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

Related Questions