简体   繁体   English

在函数中将运算符传递给 pandas 数据框:

[英]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)

st英石

f('mean','A')

will return:将返回:

tmp['A'].mean()

IIUC, use getattr : IIUC,使用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

As the complement of @mozway answer, you can use agg :作为@mozway 答案的补充,您可以使用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 .看看这里agg的最后几行代码:它已经使用了getattr

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

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