我有一個看起來像的數據框Country | IndicatorName | ValueSpain | Indicator1 | 3Spain | Indicator2 | 4Germany | Indicator16 | 24......我想將它轉換成一個帶有 IndicatorName 列、Country 行和 Value 交叉點的數據框Country | Indicator 1 | Indicator 2 | Indicator 3 | ......Spain | 3 | 4 | 16 | ......Germany | 23 | 232 | 232 | .............我正在嘗試通過 groupby(["IndicatorName","Value"]) 但不知道如何繼續import pandas as pdindicators = pd.read_csv("Indicators.csv")indicators.groupbby(["IndicatorName","Value"]).....有沒有合適的方法來處理這個問題還是需要通過迭代來完成?
1 回答

慕后森
TA貢獻1802條經驗 獲得超5個贊
我不確定初始 df 格式,因為所需的 df 似乎具有不同的值。
下面的有用嗎?
df = pd.DataFrame({'Country' : ['Spain', 'Spain', 'Germany'],
'IndicatorName':['Indicator1', 'Indicator2', 'Indicator16'],
'Value':[3, 4, 24]
})
df.pivot(index = 'Country', columns='IndicatorName', values='Value').fillna(0)
IndicatorName Indicator1 Indicator16 Indicator2
Country
Germany 0.0 24.0 0.0
Spain 3.0 0.0 4.0
添加回答
舉報
0/150
提交
取消