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

Pandas get the combined sum of each row and colum

I’m trying to add the "vertical" and "horizontal" sum for each cell.

enter image description here

So far I’ve tired to get the sum of each row and column. But like this I’d have to iterate over every value and add them which seems quite inefficient.

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

You could combine sum() and sum(1) to create a new dataframe but then the cell in question is counted twice.

Used df :

df = pd.DataFrame([[1,3], [8,4]], columns=list("ab"))

Is there any simple operation to archive the wanted result?

>Solution :

IIUC use numpy broadcasting and subtract original DataFrame:

out = df.sum().to_numpy() + df.sum(1).to_numpy()[:, None] - df
print (out)
    a   b
0  12   8
1  13  15
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