Мы можем использовать pivot
для присвоения значений US
:
dff=pd.DataFrame({'country':['US','US','UK','UK','FR','FR','ES','ES'],'type':['A','B','C','B','A','C','A','B'],'sales':[100,200,100,100,50,10,20,40]})
#use as_index=False to keep group keys within the dataframe
grouped=dff.groupby(['country','type'],as_index=False)['sales'].sum()
grouped.loc[lambda x: x.country.eq("US"), "sales"] = (grouped
#filter out US
#and search for A and B in the type column
.query("country != 'US' and type in ['A','B']")
.pivot(columns='type',values='sales')
.sum()
.array)
grouped
country type sales
0 ES A 20
1 ES B 40
2 FR A 50
3 FR C 10
4 UK B 100
5 UK C 100
6 US A 70
7 US B 140