如何将mean()作为输入参数传递给Python中的另一个函数?
我有数据,我需要通过平均值或中位数进行分组。我想为此编写一个函数。这就是我到目前为止所尝试的如何将mean()作为输入参数传递给Python中的另一个函数?,python,numpy,python-3.6,pandas-groupby,Python,Numpy,Python 3.6,Pandas Groupby,我有数据,我需要通过平均值或中位数进行分组。我想为此编写一个函数。这就是我到目前为止所尝试的 def clean(data, met = np.mean): data_grouped = data.groupby(['zipcode','neighbourhood'], as_index=False).met()[['zipcode', 'neighbourhood','revenue']] return data_grouped 这会抛出一个错误 AttributeError: 'D
def clean(data, met = np.mean):
data_grouped = data.groupby(['zipcode','neighbourhood'], as_index=False).met()[['zipcode', 'neighbourhood','revenue']]
return data_grouped
这会抛出一个错误
AttributeError: 'DataFrameGroupBy' object has no attribute 'met'
我该怎么做呢?试试这个:
您可以在最后将met
更改为median
(而不是mean
),但对我来说,它只在我指定实际的groupby
方法时起作用(而不是使用numpy
)
另外,请注意,met
出现在表达式的开头,而不是结尾
def clean(data, met = pandas.core.groupby.groupby.SeriesGroupBy.mean):
return met(data.groupby(['zipcode','neighbourhood'], as_index=False)['zipcode', 'neighbourhood','revenue'])
它在另一个数据集上对我起了作用你有没有考虑过
met(data.groupby(['zipcode','neighborhood',as_index=False))[[zipcode','neighborhood','revenue']
?groupby().met()
表示将met
视为一种方法。方法是属性,因此存在错误。np.mean
和np.media
是numpy函数,而不是groupby
对象的方法。您可以将方法名称作为字符串met='mean'
传递,然后使用操作符。methodcaller(method,)()