我正在尝试创建一个函数,该函数将在 Pandas 系列上添加某些操作。例如,假设我们有这个数据框。
import numpy as np
import pandas as pd
def get_info(df, series, func):
return df[Series].func
data = np.random.randint(10, size= (3, 4))
df = pd.DataFrame(data, columns= ['a', 'b', 'c', 'd'])
a b c d
0 3 1 3 7
1 6 8 8 3
2 9 4 4 9
这里 'd' 系列的平均值是 df.d.mean() = 6.3。
相反,我想使用我的功能: mn = get_info(df, 'd', mean())
但它遇到错误 NameError: name 'mean' is not defined
有没有办法实现这一目标?
这是你可以做的,在评论中解释:
def get_info(df, series, func):
# check if the method is implemented
if hasattr(df[series], func):
# get the method
f = getattr(df[series], func)
# check if the method is callable
if callable(f):
# call the method
return f()
else:
return "Method is not callable"
else:
return "Method is not implemented"
# example usage
get_info(df, 'd', 'mean')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句