Summing rows in Python Dataframe

前端 未结 2 1828
不思量自难忘°
不思量自难忘° 2021-01-07 11:15

I just started learning Python so forgive me if this question has already been answered somewhere else. I want to create a new column called \"Sum\", which will simply be th

相关标签:
2条回答
  • 2021-01-07 11:54
    l = ['VCIT' , VCLT' ,PCY' ... 'EWL']
    Risk_Parity['sum'] = 0
    for item in l:
        Risk_Parity['sum'] += Risk_Parity[item]
    
    0 讨论(0)
  • 2021-01-07 12:14

    Use sum with the parameter axis=1 to specify summation over rows

    Risk_Parity['Sum'] = Risk_Parity.sum(1)
    

    To create a new copy of Risk_Parity without writing a new column to the original

    Risk_Parity.assign(Sum= Risk_Parity.sum(1))
    

    Notice also, that I named the column Sum and not sum. I did this to avoid colliding with the very same method named sum I used to create the column.


    To only include numeric columns... however, sum knows to skip non-numeric columns anyway.

    RiskParity.assign(Sum=RiskParity.select_dtypes(['number']).sum(1))
    # same as
    # RiskParity.assign(Sum=RiskParity.sum(1))
    
                 VCIT   VCLT    PCY   RWR    IJR    XLU    EWL     Sum
    Date                                                              
    2017-01-31  21.70  11.73   9.59  8.28   5.06   7.01   7.95   71.33
    2017-02-28  19.84  10.75   9.58  7.55   5.07   7.45   7.95   68.19
    2017-03-31  19.99  10.75   9.59  7.37   5.02   7.40   7.65   67.79
    2017-04-30  18.90  11.10  10.02  9.67   5.90   7.40  11.28   74.27
    2017-05-31  63.96  23.67  46.02  9.92  15.23  12.34  20.41  191.55
    
    0 讨论(0)
提交回复
热议问题