Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop sum excluding one column of pandas dataframe

I have a dataframe as the following:

import pandas as pd
df = pd.DataFrame([(1,2,3,4,5,6),
                   (1,2,3,4,5,6),
                   (1,2,3,4,5,6)], columns=['a','b','c','d','e','f'])

Out:
    a b c d e f
0   1 2 3 4 5 6
1   1 2 3 4 5 6 
2   1 2 3 4 5 6

and I want to get the sum of all the elements of the dataframe, always excluding one column. In this example the desired outcome would be:

60 57 54 51 48 45

I have found a solution that seems to do the job, but I’m pretty sure there must be a more efficient way to do the same:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for x in df.columns:
    df.drop(columns = x).sum().sum()

>Solution :

Use DataFrame.rsub for subtract from right side summed rows by df.sum(axis=1), last add sum for sum per columns:

s = df.rsub(df.sum(axis=1), axis=0).sum()
print (s)
a    60
b    57
c    54
d    51
e    48
f    45
dtype: int64
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading