【发布时间】:2019-06-12 15:41:10
【问题描述】:
我有一个计算熊猫数据框列模式的函数:
def my_func(df):
for col in df.columns:
stat = df[col].mode()
print(stat)
但我想让它更通用,以便我可以更改我计算的统计数据,例如mean, max,... 我试图将方法 mode() 作为参数传递给我的函数:
def my_func(df, pandas_stat):
for col in df.columns:
stat = df[col].pandas_stat()
print(stat)
已提及:How do I pass a method as a parameter in Python
但这似乎对我不起作用。 用一个简单的例子:
> A
a b
0 1.0 2.0
1 2.0 4.0
2 2.0 6.0
3 3.0 NaN
4 NaN 4.0
5 3.0 NaN
6 2.0 6.0
7 4.0 6.0
不识别命令模式:
> my_func(A, mode)
Traceback (most recent call last):
File "<ipython-input-332-c137de83a530>", line 1, in <module>
my_func(A, mode)
NameError: name 'mode' is not defined
所以我尝试了 pd.DataFrame.mode:
> my_func(A, pd.DataFrame.mode)
Traceback (most recent call last):
File "<ipython-input-334-dd913410abd0>", line 1, in <module>
my_func(A, pd.DataFrame.mode)
File "<ipython-input-329-8acf337bce92>", line 3, in my_func
stat = df[col].pandas_stat()
File "/anaconda3/envs/py36/lib/python3.6/site-packages/pandas/core/generic.py", line 4376, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'pandas_stat'
有没有办法通过mode函数?
【问题讨论】:
标签: python pandas parameter-passing