Pandas sum by groupby, but exclude certain columns

前端 未结 3 2002
孤城傲影
孤城傲影 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 11:56

    You can select the columns of a groupby:

    In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
    Out[11]:
                           Y1961  Y1962  Y1963
    Country     Item_Code
    Afghanistan 15            10     20     30
                25            10     20     30
    Angola      15            30     40     50
                25            30     40     50
    

    Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

提交回复
热议问题