'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()
Solution 1:[1]
As the complement of @mozway answer, you can use agg:
>>> tmp.agg({'A': 'mean', 'B': 'max'})
A 1.0
B 4.0
dtype: float64
Take a look at the last lines of code of agg here: it already uses getattr.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dom |
| Solution 2 | Sunderam Dubey |
