Pandas groupby()不接受带选项的apply()方法

时间:2014-04-29 04:04:24

标签: python pandas

使用以下示例:

arrays = [['one','one','one','two','two','two'],[1,2,3,1,2,3]]
df = pd.DataFrame(np.random.randn(6,2),index=pd.MultiIndex.from_tuples(zip(*arrays)),columns=['A','B'])

正如预期的那样,这适用于groupby对象:

df.groupby(level=0).apply(lambda x: pd.rolling_mean(x, window=3, center=True))

但是,在指定应用选项时会引发错误:

df.groupby(level=0).apply(lambda x: pd.rolling_mean(x, window=3, center=True), raw=True)    
TypeError: <lambda>() got an unexpected keyword argument 'raw'

我无法弄清楚我哪里出错了。

注意:它似乎适用于非MultiIndex对象

Pandas: Timing difference between Function and Apply to Series

1 个答案:

答案 0 :(得分:4)

applyDataFrame个对象有不同的GroupBy方法。只有DataFrame.apply有一个raw参数:

help(df.apply)
# Output:
Help on method apply in module pandas.core.frame:

apply(self, func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds) method of pandas.core.frame.DataFrame instance
    Applies function along input axis of DataFrame.
...

而对于groupby:

grouped = df.groupby(level=0)
help(grouped.apply)
# Output:
Help on method apply in module pandas.core.groupby:

apply(self, func, *args, **kwargs) method of pandas.core.groupby.DataFrameGroupBy instance