I have the following DataFrame called df:
| Numeric | Country1 | Country2 | Country3 | Country4 | Country5 |
|---|---|---|---|---|---|
| 5 | Yes | No | No | Yes | Yes |
| 10 | No | Yes | Yes | No | Yes |
| 6 | Yes | No | No | Yes | No |
| 8 | Yes | No | Yes | Yes | Yes |
| 9 | No | Yes | No | Yes | No |
I would like to find a way to turn the code below into a loop or function as I have many rows and many columns in my DataFrame. The first line of code below takes the sum of column Numeric, and the sum of column Country1 == "YES" values only and it inputs the output to the data frame below under row Country1 and column Country1.
The second line of the code it will take the sum of column Numeric, the sum of Colum Country1 that has YEs values, and the sum of column Country2 == "Yes". The output of this line gets entered into row name Country2 and column name Country1.
This pattern continues for row Country3, Country4 and Country 5. I found a way to hard coded but I would like to find a more efficient way of doing it.
df1.loc["Country1", "Country1"] = df.loc[(df['Country1'] == "Yes"), 'Numeric'].sum()
df1.loc["Country2", "Country1"] = df.loc[(df['Country2'] == "Yes") & (df['Country1'] == "Yes"), 'Numeric'].sum()
df1.loc["Country3", "Country1"] = df.loc[(df['Country3'] == "Yes") &(df['Country1'] == "Yes"), 'Numeric'].sum()
df1.loc["Country4", "Country1"] = df.loc[(df['Country4'] == "Yes") &(df['Country1'] == "Yes"), 'Numeric'].sum()
df1.loc["Country5", "Country1"] = df.loc[(df['Country5'] == "Yes") &(df['Country1'] == "Yes"), 'Numeric'].sum()
The desired output will look like the DataFrame below. I just created the dataframe to show where each values goes but the numbers entered below are not accurate. Is just to illustrate an example.
| Country1 | Country2 | Country3 | Country4 | Country5 | |
|---|---|---|---|---|---|
| Country1 | 5 | 3 | 19 | 8 | 8 |
| Country2 | 10 | 0 | 20 | 7 | 7 |
| Country3 | 15 | 8 | 1 | 4 | 7 |
| Country4 | 20 | 9 | 3 | 8 | 5 |
| Country5 | 2 | 10 | 5 | 9 | 4 |
Thank you!