简体   繁体   English

Python中不同方法如何合并

[英]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 ?有没有办法以更简洁的方式复制这行代码,有没有办法loop或创建function

This might not be best practice (because of eval ) but you could avoid to repeat yourself by storing your results in a dictionary:这可能不是最佳实践(因为eval ),但您可以通过将结果存储在字典中来避免重复自己:

impute = dict()

for fun in ["mean", "median", "mode"]:
    impute[fun] = eval(f"df['column'].fillna(value=df['column'].{fun}())")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM