2

I have a function which goes something like:

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')

I was wondering if there's a more elegant, one liner, way to do so. There is getattr which would be great if it worked on methods. Is there something similar?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Eric Johnson
  • 682
  • 1
  • 12

1 Answers1

4

IIUC use:

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')

Thank you for comment @Himanshu Poddar , if never calc_type is invalid solution is:

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

EDIT: If need to use getattr use:

out = getattr(s, calc_type)()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252