如何使用 pandas 转置一半的数据帧
How to transpose half of the dataframe using pandas
我有一个数据框
cycle_end_date
mid_cycle
Total
0
1
2
3
15th Sept
230
600
100
200
50
10
我想转置这个数据框,例如:
cycle_end_date
mid_cycle
Total
Delay
new_col
15th Sept
230
600
0
100
15th Sept
230
600
1
200
15th Sept
230
600
2
50
15th Sept
230
600
3
10
基本上,第 0 天、第 1 天、第 2 天列将成为 mid_cycle
下的行,并且 total_amt, pending_amt
将相应地分配。
我们如何实现这一目标? .transpose()
没有给我想要的结果。
使用melt
:
out = df.melt(id_vars=['cycle_end_date', 'mid_cycle', 'Total'],
var_name='Delay', value_name='new_col')
print(out)
# Output
cycle_end_date mid_cycle Total Delay new_col
0 15th Sept 230 600 0 100
1 15th Sept 230 600 1 200
2 15th Sept 230 600 2 50
3 15th Sept 230 600 3 10
我有一个数据框
cycle_end_date | mid_cycle | Total | 0 | 1 | 2 | 3 |
---|---|---|---|---|---|---|
15th Sept | 230 | 600 | 100 | 200 | 50 | 10 |
我想转置这个数据框,例如:
cycle_end_date | mid_cycle | Total | Delay | new_col |
---|---|---|---|---|
15th Sept | 230 | 600 | 0 | 100 |
15th Sept | 230 | 600 | 1 | 200 |
15th Sept | 230 | 600 | 2 | 50 |
15th Sept | 230 | 600 | 3 | 10 |
基本上,第 0 天、第 1 天、第 2 天列将成为 mid_cycle
下的行,并且 total_amt, pending_amt
将相应地分配。
我们如何实现这一目标? .transpose()
没有给我想要的结果。
使用melt
:
out = df.melt(id_vars=['cycle_end_date', 'mid_cycle', 'Total'],
var_name='Delay', value_name='new_col')
print(out)
# Output
cycle_end_date mid_cycle Total Delay new_col
0 15th Sept 230 600 0 100
1 15th Sept 230 600 1 200
2 15th Sept 230 600 2 50
3 15th Sept 230 600 3 10