Groupby in python pandas: Fast Way

前端 未结 2 950
挽巷
挽巷 2020-12-07 17:32

I want to improve the time of a groupby in python pandas. I have this code:

df[\"Nbcontrats\"] = df.groupby([\'Client\', \'Month\'])[\'Contrat\         


        
2条回答
  •  半阙折子戏
    2020-12-07 17:38

    With the DataFrameGroupBy.size method:

    df.set_index(['Client', 'Month'], inplace=True)
    df['Nbcontrats'] = df.groupby(level=(0,1)).size()
    df.reset_index(inplace=True)
    

    The most work goes into assigning the result back into a column of the source DataFrame.

提交回复
热议问题