在熊猫中交换轴

时间:2013-04-30 13:48:05

标签: python indexing pandas swap

交换Pandas Dataframe轴的最有效方法是什么?

例如,如何将df1转换为df2以下?

In [2]: import pandas as pd

In [3]: df1 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})

In [4]: df1
Out[4]: 
   one  two
0    1    4
1    2    3
2    3    2
3    4    1

In [5]: df2 = pd.DataFrame({0 : [1,4], 1 : [2,3], 2 : [3,2], 3 : [4,1]}, index=['one','two'])

In [6]: df2
Out[6]: 
     0  1  2  3
one  1  2  3  4
two  4  3  2  1

1 个答案:

答案 0 :(得分:17)

transpose

处获取战利品
In [4]: df1.T
Out[4]: 
     0  1  2  3
one  1  2  3  4 
two  4  3  2  1