Stefano Potter
Stefano Potter

Reputation: 3577

Function which applies a groupby

I have numerous dataframes I want to apply a function to.

My dataframes look like this:

Year  ID   Pressure
1984  1    0.2
1985  2    0.5
1986  3    0.7

I am trying:

def f(x):
   return x.groupby(['ID']).Pressure.mean().to_frame().reset_index()

#apply the function to dataframes
df.apply(f)
df2.apply(f)

but this returns:

 KeyError: ('ID', u'occurred at index Year')

without a function I can do what I want like this:

df=df.groupby(['ID']).Pressure.mean().to_frame().reset_index()

Upvotes: 0

Views: 50

Answers (1)

Steven G
Steven G

Reputation: 17122

apply is used when you want to apply a function to every values of a dataframe. since you just want to apply something to the entire df you should just do:

f(df)
f(df2)

Upvotes: 1

Related Questions