grouping pandas dataframe by two columns (or more)?

前端 未结 1 1430
野趣味
野趣味 2021-02-14 02:00

I have the following dataframe:

mydf = pandas.DataFrame({\"cat\": [\"first\", \"first\", \"first\", \"second\", \"second\", \"third\"], \"class\": [\"A\", \"A\",         


        
1条回答
  •  伪装坚强ぢ
    2021-02-14 02:25

    Use reset_index

    In [9]: mydf.groupby(['cat', "class"]).val.sum().reset_index()
    Out[9]: 
          cat class  val
    0   first     A    7
    1  second     B    3
    2   third     C   10
    

    EDIT

    set level=1 if you want to set cat as index

    In [10]: mydf.groupby(['cat', "class"]).val.sum().reset_index(level=1)
    Out[10]: 
           class  val
    cat              
    first      A    7
    second     B    3
    third      C   10
    

    You can also set as_index=False to get the same output

    In [29]: mydf.groupby(['cat', "class"], as_index=False).val.sum()
    Out[29]: 
          cat class  val
    0   first     A    7
    1  second     B    3
    2   third     C   10
    

    0 讨论(0)
提交回复
热议问题