Reputation: 2959
I have a dummy data frame as follows
import pandas as pd
df=pd.DataFrame({
'ID':[1,1,2,2,2,3,4,5,5],
'workday':[1,2,1,2,3,1,1,1,2]
})
I have these two aggregate functions
df.groupby('ID').agg(['first','last'])
df.groupby('ID').agg('nth',-2)
I tried lambda x: x.nth(-2)
but it says AttributeError: 'Series' object has no attribute 'nth'
I want to pass them at once in one groupby aggregate function
Upvotes: 1
Views: 166
Reputation: 862691
One idea:
df = df.groupby('ID').agg(['first','last', lambda x: x.iloc[-2] if len(x) > 1 else np.nan])
print (df)
workday
first last <lambda_0>
ID
1 1 2 1.0
2 1 3 2.0
3 1 1 NaN
4 1 1 NaN
5 1 2 1.0
Upvotes: 1