Pandas sum by groupby, but exclude certain columns

前端 未结 3 1996
孤城傲影
孤城傲影 2020-11-27 11:02

What is the best way to do a groupby on a Pandas dataframe, but exclude some columns from that groupby? e.g. I have the following dataframe:



        
3条回答
  •  眼角桃花
    2020-11-27 12:09

    If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:

    columns = ['Y'+str(i) for year in range(1967, 2011)]
    
    df.groupby('Country')[columns].agg('sum')
    

提交回复
热议问题