Pandas 熊猫支点?桌子?熔化堆叠还是取消堆叠?
我有一个如下所示的数据帧:Pandas 熊猫支点?桌子?熔化堆叠还是取消堆叠?,pandas,pivot,melt,Pandas,Pivot,Melt,我有一个如下所示的数据帧: id Revenue Cost qty time 0 A 400 50 2 1 1 A 900 200 8 2 2 A 800 100 8 3 3 B 300 20 1 1 4 B 600 150 4 2 5 B
id Revenue Cost qty time
0 A 400 50 2 1
1 A 900 200 8 2
2 A 800 100 8 3
3 B 300 20 1 1
4 B 600 150 4 2
5 B 650 155 4 3
Revenue qty Cost
1 2 3 1 2 3 1 2 3
我正试图做到这一点:
id Type 1 2 3
0 A Revenue 400 900 800
1 A Cost 50 200 100
2 A qty 2 8 8
3 B Revenue 300 600 650
4 B Cost 20 150 155
5 B qty 1 4 4
时间总是在1-3之间重复,所以我需要在1-3列中转置或旋转时间
以下是我迄今为止所尝试的:
pd.pivot_table(df, values = ['Revenue', 'qty', 'Cost'] , index=['id'], columns='time').reset_index()
但这只是一张非常长的桌子,将所有东西并排放置,而不是像这样堆叠:
id Revenue Cost qty time
0 A 400 50 2 1
1 A 900 200 8 2
2 A 800 100 8 3
3 B 300 20 1 1
4 B 600 150 4 2
5 B 650 155 4 3
Revenue qty Cost
1 2 3 1 2 3 1 2 3
在这种情况下,我需要将收入、数量和成本转换为一行,只使用1、2、3作为列名。因此,每个“类型”的ID都是重复的,但根据时间1-3列出它。我们仍然可以执行
取消堆叠和堆叠
df.set_index(['id','time']).stack().unstack(level=1).reset_index()
Out[24]:
time id level_1 1 2 3
0 A Revenue 400 900 800
1 A Cost 50 200 100
2 A qty 2 8 8
3 B Revenue 300 600 650
4 B Cost 20 150 155
5 B qty 1 4 4
另一种选择是使用熊猫1.1.0并在其上:
(df
.melt(["id", "time"])
.pivot(["id", "variable"], "time", "value")
.reset_index()
.rename_axis(columns=None)
)
id variable 1 2 3
0 A Cost 50 200 100
1 A Revenue 400 900 800
2 A qty 2 8 8
3 B Cost 20 150 155
4 B Revenue 300 600 650
5 B qty 1 4 4