如何在Pandas DataFrame中移动列而不会丢失值

Vix*_*are 2 python dataframe pandas

我想在Pandas DataFrame中移动一列,但是我没有找到一种方法来做到这一点而不会丢失值.(这篇文章非常类似于如何在Pandas DataFrame中移动一列,但经验证的答案没有给出所需的输出,我无法对其进行评论).有谁知道怎么做?

##    x1   x2
##0  206  214
##1  226  234
##2  245  253
##3  265  272
##4  283  291
Run Code Online (Sandbox Code Playgroud)

期望的输出:

##    x1   x2
##0  206  nan
##1  226  214
##2  245  234
##3  265  253
##4  283  271
##5  nan  291
Run Code Online (Sandbox Code Playgroud)

roo*_*oot 6

用于loc向DataFrame添加新的空行,然后执行移位.

df.loc[max(df.index)+1, :] = None
df.x2 = df.x2.shift(1)
Run Code Online (Sandbox Code Playgroud)

上面的代码假设您的索引是基于整数的,这是pandas的默认值.如果您使用的是基于非整数的索引,请替换max(df.index)+1为您想要的新最后一个索引.