如何在Pandas DataFrame中移动一列

我想在Pandas DataFrame移动一个列,但是我没有find一个方法来从文档中完成,而没有重写整个DF。 有谁知道如何做到这一点? dataframe:

 ## x1 x2 ##0 206 214 ##1 226 234 ##2 245 253 ##3 265 272 ##4 283 291 

期望的输出:

 ## x1 x2 ##0 206 nan ##1 226 214 ##2 245 234 ##3 265 253 ##4 283 272 ##5 nan 291 
 In [18]: a Out[18]: x1 x2 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 In [19]: a.x2 = a.x2.shift(1) In [20]: a Out[20]: x1 x2 0 0 NaN 1 1 5 2 2 6 3 3 7 4 4 8 

如果您不希望丢失超过数据框末尾的列,请首先添加所需的数字:

  offset = 5 DF = DF.append([np.nan for x in range(offset)]) DF = DF.shift(periods=offset) DF = DF.reset_index() #Only works if sequential index 

我想import

 import pandas as pd import numpy as np 

首先在DataFrame( df )的末尾添加NaN, NaN,...新行。

 s1 = df.iloc[0] # copy 1st row to a new Series s1 s1[:] = np.NaN # set all values to NaN df2 = df.append(s1, ignore_index=True) # add s1 to the end of df 

它将创build新的DF DF2。 也许有更优雅的方式,但这个工程。

现在你可以改变它:

 df2.x2 = df2.x2.shift(1) # shift what you want