У меня есть пандас DataFrame с двумя измерениями region
и products
и двумя мерами cost
и price
:
df = pd.DataFrame(
{'region':['N', 'S', 'W', 'E', 'N', 'S', 'W', 'E'],
'product':['P1', 'P1', 'P1', 'P1', 'P2', 'P2', 'P2', 'P2'],
'cost':[10, 13, 17, 28, 29, 23, 17, 18],
'price':[7, 8, 4, 11, 9, 13, 7, 8]})
Я хочу получить:
region E N S W
price cost price cost price cost price cost
product
P1 11 28 ...
P2 8 18 ...
Я пытался:
df1 = df.groupby(['product', 'region'])
.agg({'price': 'first', 'cost': 'first'})
.unstack('region')
.swaplevel(axis=1)
print(df1)
Но я получаю:
region E N S W E N S W
price price price price cost cost cost cost
product
P1 11 7 8 4 28 10 13 17
P2 8 9 13 7 18 29 23 17
Что мне не хватает?