繁体   English   中英

如何以python方式返回不同的数据框列计算

[英]How to pythonically return different dataframe column calculations

我有一个类似的功能:

import pandas as pd
import numpy as np


def my_fun(df, calc_type):
    if calc_type == 'sum':
        return df['col_name'].sum()
    elif calc_type == 'mean': 
        return df['col_name'].mean()
    elif calc_type == 'std': 
        return df['col_name'].std()

# sample df
df = pd.DataFrame({'col_name': np.random.normal(25, 3.5, 1000)})

# function call
my_func(df, 'sum')

我想知道是否有更优雅的单班轮方式来做到这一点。 如果它适用于方法,那么getattr会很棒。 有没有类似的东西?

IIUC 用途:

def my_fun(df, calc_type):
      #specify possible functions 
     if calc_type in ['sum','mean','min','max', 'std']:
         return df['col_name'].agg(calc_type)
     else:
         print ('wrong calc_type')

感谢@Himanshu Poddar 的评论,如果从来没有 calc_type 是无效的解决方案是:

def my_fun(df, calc_type):
    return df['col_name'].agg(calc_type)

编辑:如果需要使用getattr使用:

out = getattr(s, calc_type)()

暂无
暂无

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

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