There exist the following dataframe:
year | pop0 | pop1 | city0 | city1 |
---|---|---|---|---|
2019 | 20 | 40 | Malibu | NYC |
2018 | 8 | 60 | Sydney | Dublin |
2018 | 36 | 23 | NYC | Malibu |
2020 | 17 | 44 | Malibu | NYC |
2019 | 5 | 55 | Sydney | Dublin |
I would like to calculate the weighted average for the population of each city pair as a new column. For example, the w_mean
for Malibu / NYC = (23+20+17)/(36+40+44) = 0.5.
Following is the desired output:
year | pop0 | pop1 | city0 | city1 | w_mean |
---|---|---|---|---|---|
2018 | 23 | 36 | Malibu | NYC | 0.5 |
2019 | 20 | 40 | Malibu | NYC | 0.5 |
2020 | 17 | 44 | Malibu | NYC | 0.5 |
2018 | 8 | 60 | Sydney | Dublin | 0.113 |
2019 | 5 | 55 | Sydney | Dublin | 0.113 |
I already sorted the dataframe by its columns, but I have issues swapping the 3rd row from NYC/Malibu to Malibu/NYC with its populations. Besides that, I can only calculate the w_mean
for each row but not for each group. I tried groupby().mean()
but didn't get any useful output.
Current code:
import pandas as pd
data = pd.DataFrame({'year': ["2019", "2018", "2018", "2020", "2019"], 'pop0': [20,8,36,17,5], 'pop1': [40,60,23,44,55], 'city0': ['Malibu','Sydney','NYC','Malibu','Sydney'], 'city1': ['NYC','Dublin','Malibu','NYC','Dublin']})
new = data.sort_values(by=['city0', 'city1'])
new['w_mean'] = new.apply(lambda row: row.pop0 / row.pop1, axis=1)
print(new)