重塑熊猫数据框,其中列类别变为单独的列

时间:2019-04-03 06:31:51

标签: python pandas dataframe reshape transpose

我想更改重塑熊猫数据框。我使用了stack()并尝试了其他不同的方式,但是无法做到这一点。

我的数据框紧随其后。

data = [[1, 'Electricity', 100], [1, 'Water', 10],[1, 'LPG', 50.1], 
        [2, 'Electricity', 200], [2, 'Water', 15],[2, 'LPG', 500], 
        [3, 'Electricity', 500], [3, 'Water', ],[3, 'LPG', 60.6] ] 

df = pd.DataFrame(data, columns = ['siteId', 'utility', 'consumption']) 
df

enter image description here

这是我想要的输出。

+------+-----------+-----------+
|siteId|Electricity|Water |LPG |
+------+-----------+------+----+
|1     |100        |10.0  |50.1|
|2     |200        |15.0  |500 |
|3     |500        |      |60.6|
+------+-----------+------+----+

0 个答案:

没有答案