![](/img/trans.png)
[英]Pandas, Python: How to turn a row value into column and aggregate the values of another column as sum
[英]How to aggregate sum, and convert unique row values to column names, in pandas?
我有熊貓pd.groupby()
函數的問題。 我有數據框
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()
但它對我來說根本不起作用。
.groupby
然后.unstack
正確的級別。
level=2
是來自.groupby
對象的'Measure'
列。.reset_index
刪除多級索引。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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.