How to rearrange Pandas column sequence?

后端 未结 6 540
暗喜
暗喜 2020-12-08 05:16
>>> df =DataFrame({\'a\':[1,2,3,4],\'b\':[2,4,6,8]})
>>> df[\'x\']=df.a + df.b
>>> df[\'y\']=df.a - df.b
>>> df
   a  b   x  y
0          


        
6条回答
  •  天涯浪人
    2020-12-08 05:44

    Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.

    In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
    Out[61]: 
        x  y  a  b
    0   3 -1  1  2
    1   6 -2  2  4
    2   9 -3  3  6
    3  12 -4  4  8
    

提交回复
热议问题