Python 将参数传递给groupby聚合中的函数
我有一个虚拟数据框,如下所示Python 将参数传递给groupby聚合中的函数,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我有一个虚拟数据框,如下所示 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] }) 我有两个聚合函数 df.groupby('ID').agg(['first','last']) df.groupby('ID').agg('nth',-2) 我试过lambda x:x.nth(-2)但它说AttributeError:'Seri
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]
})
我有两个聚合函数
df.groupby('ID').agg(['first','last'])
df.groupby('ID').agg('nth',-2)
我试过lambda x:x.nth(-2)
但它说AttributeError:'Series'对象没有属性'nth'
我想在一个groupby聚合函数中立即传递它们一个想法:
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
df=df.groupby('ID').agg(['first','last',lambda x:x.iloc[-2]如果len(x)>1 else np.nan])
打印(df)
工作日
最后一个
身份证件
1 1 2 1.0
2 1 3 2.0
311南
41NAN
5 1 2 1.0