I have a dataframe that looks like this:
from random import randint
import pandas as pd
df = pd.DataFrame({"ID": ["a", "b", "c", "d", "e", "f", "g"],
"Size": [randint(0,9) for i in range(0,7)]})
df
ID Size
0 a 4
1 b 3
2 c 0
3 d 2
4 e 9
5 f 5
6 g 3
And what I would like to obtain is this (could be a matrix as well):
sums_df
a b c d e f g
a 8.0 7.0 4.0 6.0 13.0 9.0 7.0
b 7.0 6.0 3.0 5.0 12.0 8.0 6.0
c 4.0 3.0 0.0 2.0 9.0 5.0 3.0
d 6.0 5.0 2.0 4.0 11.0 7.0 5.0
e 13.0 12.0 9.0 11.0 18.0 14.0 12.0
f 9.0 8.0 5.0 7.0 14.0 10.0 8.0
g 7.0 6.0 3.0 5.0 12.0 8.0 6.0
That is, the sum of Size values for all possible pairs in ID.
For now I have this simple but unefficient code:
sums_df = pd.DataFrame()
for i in range(len(df)):
for j in range(len(df)):
sums_df.loc[i,j] = df.Size[i] + df.Size[j]
sums_df.index = list(df.ID)
sums_df.columns = list(df.ID)
It works fine for small examples like this, but for my actual data it gets too long and I am sure it is possible to avoid the nested for loops. Can you think of a better way to do this ?
Thanks for any help !