我有一个df1形状的数据框
import pandas as pd
df1 = pd.DataFrame({
'From': ['A','B','C'],
'To': ['X','Y','Z'],
'Price': [1,2,3]
})
我想做的是将df1重塑为df2的形式。所需的最终结果将是这样:
df2 = pd.DataFrame({
'Location': ['A','X','B','Y','C','Z'],
'Direction': ['Origin','Destination','Origin','Destination','Origin','Destination'],
'Price': [1,1,2,2,3,3]
})
我想用pandas stack(),pivot(),melt()等来实现,但是我不知道它是如何完成的。
答案 0 :(得分:3)
首先放置rename
列,然后通过DataFrame.set_index
和DataFrame.stack
重塑形状:
df = (df1.rename(columns={'From':'Origin','To':'Destination'})
.set_index('Price')
.rename_axis('Direction', axis=1)
.stack()
.reset_index(name='Location')
.reindex(['Location','Direction','Price'], axis=1))
print (df)
Location Direction Price
0 A Origin 1
1 X Destination 1
2 B Origin 2
3 Y Destination 2
4 C Origin 3
5 Z Destination 3
如果顺序不重要:
df2 = (df1.rename(columns={'From':'Origin','To':'Destination'})
.melt('Price',var_name='Direction',value_name='Location')
.reindex(['Location','Direction','Price'], axis=1)
)
print (df2)
Location Direction Price
0 A Origin 1
1 B Origin 2
2 C Origin 3
3 X Destination 1
4 Y Destination 2
5 Z Destination 3