sanguineturtle
sanguineturtle

Reputation: 1465

Pandas groupby() not accepting apply() method with options

Using the following example:

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'])

As expected this apply works over the groupby object:

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

However, when specifying options for apply it throws up an error:

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'

I can't figure out where I have gone wrong.

Note: It seems to work fine for non MultiIndex objects

Pandas: Timing difference between Function and Apply to Series

Upvotes: 4

Views: 2019

Answers (1)

Marius
Marius

Reputation: 60230

There are different apply methods for DataFrames and GroupBy objects. Only DataFrame.apply has a raw argument:

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.
...

Whereas for the 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

Upvotes: 4

Related Questions