Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing operators to pandas dataframe in function:

Say I want to iterate say I have pandas dataframe:

import pandas as pd
tmp = pd.DataFrame([(2,2),(0,4),(1,3)],columns= ['A','B'])

and I want to write something of the following kind:

def f(operator,column)

s.t

f('mean','A')

will return:

tmp['A'].mean()
like image 916
Itay Avatar asked Oct 15 '25 22:10

Itay


1 Answers

IIUC, use getattr:

tmp = pd.DataFrame([(2,2),(0,4),(1,3)], columns=['A','B'])

def f(operator, column):
    return getattr(tmp[column], operator)()

f('mean', 'A')
# 1.0

f('max', 'B')
# 4
like image 79
mozway Avatar answered Oct 18 '25 11:10

mozway