如何在Pandas DataFrame中移动列 [英] How to shift a column in Pandas DataFrame

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

问题描述

我想在Pandas DataFrame 中移动一列,但是我无法找到一种从文档中执行的方法,而无需重写整个DF 。有人知道该怎么做吗?
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 from the documentation without rewriting the whole DF. Does anyone know how to do it? 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  271
##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

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

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