How do I create a sum row and sum column in pandas?

后端 未结 4 442
刺人心
刺人心 2020-12-08 06:55

I\'m going through the Khan Academy course on Statistics as a bit of a refresher from my college days, and as a way to get me up to speed on pandas & other scientific Py

4条回答
  •  隐瞒了意图╮
    2020-12-08 07:40

    Or in two steps, using the .sum() function as you suggested (which might be a bit more readable as well):

    import pandas as pd
    
    df = pd.DataFrame( {"Undergraduate": {"Straight A's": 240, "Not": 3_760},"Graduate": {"Straight A's": 60, "Not": 440},})
    
    #Total sum per column: 
    df.loc['Total',:]= df.sum(axis=0)
    
    #Total sum per row: 
    df.loc[:,'Total'] = df.sum(axis=1)
    

    Output:

                  Graduate  Undergraduate  Total
    Not                440           3760   4200
    Straight A's        60            240    300
    Total              500           4000   4500
    

提交回复
热议问题