慕運(yùn)維8079593
2023-10-06 10:56:47
我對(duì) pandas 功能有疑問pd.groupby()。我有數(shù)據(jù)框data = [{'Shop': 'Venga', 'Item Name': 'Oranges', 'Measure':'Supply Cost', 'Value': '10'}, {'Shop': 'Venga', 'Item Name': 'Oranges', 'Measure':'Product Cost', 'Value': '20'}, {'Shop': 'Venga', 'Item Name': 'Apples', 'Measure':'Supply Cost', 'Value': '5'}, {'Shop': 'Venga', 'Item Name': 'Apples', 'Measure':'Product Cost', 'Value': '60'}, {'Shop': 'Mesto', 'Item Name': 'Oranges', 'Measure':'Supply Cost', 'Value': '15'}, {'Shop': 'Mesto', 'Item Name': 'Oranges', 'Measure':'Product Cost', 'Value': '10'}, {'Shop': 'Mesto', 'Item Name': 'Apples', 'Measure':'Supply Cost', 'Value': '80'}, {'Shop': 'Mesto', 'Item Name': 'Apples', 'Measure':'Product Cost', 'Value': '5'}, ]我想將我的類別移至Measure列并使其看起來像這樣:我嘗試過跑步,data.groupby(['Measure'], axis = 1).sum()但對(duì)我來說根本不起作用。
1 回答

長(zhǎng)風(fēng)秋雁
TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
.groupby
然后使用.unstack
正確的級(jí)別。在本例中,
level=2
是'Measure'
來自.groupby
對(duì)象的列。
.reset_index
刪除多級(jí)索引。
import pandas as pd
dfg = df.groupby(['Shop', 'Item Name', 'Measure'])['Value'].sum().unstack(level=2).reset_index()
dfg.columns.name = None
# display(dfg)
? ? Shop Item Name Product Cost Supply Cost
0? Mesto? ? Apples? ? ? ? ? ? 5? ? ? ? ? 80
1? Mesto? ?Oranges? ? ? ? ? ?10? ? ? ? ? 15
2? Venga? ? Apples? ? ? ? ? ?60? ? ? ? ? ?5
3? Venga? ?Oranges? ? ? ? ? ?20? ? ? ? ? 10
添加回答
舉報(bào)
0/150
提交
取消