如何在不丢失值的情况下在Pandas DataFrame中移动列 [英] How to shift a column in Pandas DataFrame without losing value

查看:84
本文介绍了如何在不丢失值的情况下在Pandas DataFrame中移动列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Pandas DataFrame中移动一列,但是我一直无法找到一种在不丢失值的情况下做到这一点的方法. (这篇文章非常类似于如何移动列在Pandas DataFrame中,但经过验证的答案未提供所需的输出,因此我无法对其进行评论). 有人知道怎么做吗?

I would like to shift a column in a Pandas DataFrame, but I haven't been able to find a method to do it without losing values. (This post is quite similar to How to shift a column in Pandas DataFrame but the validated answer doesn't give the desired output and I can't comment it). Does anyone know how to do it?

##    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  271
##5  nan  291

推荐答案

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

Use loc to add a new blank row to the DataFrame, then perform the shift.

df.loc[max(df.index)+1, :] = None
df.x2 = df.x2.shift(1)

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

The code above assumes that your index is integer based, which is the pandas default. If you're using a non-integer based index, replace max(df.index)+1 with whatever you want the new last index to be.

这篇关于如何在不丢失值的情况下在Pandas DataFrame中移动列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆