将参数传递给groupby聚合熊猫中的函数

时间:2020-07-23 08:03:46

标签: 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: 'Series' object has no attribute 'nth' 我想一次通过合计函数将它们传递给一个组

1 个答案:

答案 0 :(得分:1)

一个主意:

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
相关问题