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

后端 未结 4 437
刺人心
刺人心 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:32

    append and assign

    The point of this answer is to provide an in line and not an in place solution.

    append

    I use append to stack a Series or DataFrame vertically. It also creates a copy so that I can continue to chain.

    assign

    I use assign to add a column. However, the DataFrame I'm working on is in the in between nether space. So I use a lambda in the assign argument which tells Pandas to apply it to the calling DataFrame.


    df.append(df.sum().rename('Total')).assign(Total=lambda d: d.sum(1))
    
                  Graduate  Undergraduate  Total
    Not                440           3760   4200
    Straight A's        60            240    300
    Total              500           4000   4500
    

    Fun alternative

    Uses drop with errors='ignore' to get rid of potentially pre-existing Total rows and columns.

    Also, still in line.

    def tc(d):
      return d.assign(Total=d.drop('Total', errors='ignore', axis=1).sum(1))
    
    df.pipe(tc).T.pipe(tc).T
    
                  Graduate  Undergraduate  Total
    Not                440           3760   4200
    Straight A's        60            240    300
    Total              500           4000   4500
    

提交回复
热议问题