Skip to content Skip to sidebar Skip to footer

Summing Rows In Python Dataframe

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 the previou

Solution 1:

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))VCITVCLTPCYRWRIJRXLUEWLSumDate2017-01-31  21.7011.739.598.285.067.017.9571.332017-02-28  19.8410.759.587.555.077.457.9568.192017-03-31  19.9910.759.597.375.027.407.6567.792017-04-30  18.9011.1010.029.675.907.4011.2874.272017-05-31  63.9623.6746.029.9215.2312.3420.41191.55

Solution 2:

l = ['VCIT' , VCLT' ,PCY' ... 'EWL']
Risk_Parity['sum'] = 0
for item in l:
    Risk_Parity['sum'] += Risk_Parity[item]

Post a Comment for "Summing Rows In Python Dataframe"