将 pandas 数据框中的列上移一格? [英] Shift column in pandas dataframe up by one?

查看:76
本文介绍了将 pandas 数据框中的列上移一格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框.我想落后"我的专栏之一.例如,这意味着将整个列"gdp"上移一位,然后删除其余行底部的所有多余数据,以使所有列的长度再次相等.

I've got a pandas dataframe. I want to 'lag' one of my columns. Meaning, for example, shifting the entire column 'gdp' up by one, and then removing all the excess data at the bottom of the remaining rows so that all columns are of equal length again.

df =
    y  gdp  cap
0   1    2    5
1   2    3    9
2   8    7    2
3   3    4    7
4   6    7    7

df_lag =
    y  gdp  cap
0   1    3    5
1   2    7    9
2   8    4    2
3   3    7    7

是否要这样做?

推荐答案

In [44]: df['gdp'] = df['gdp'].shift(-1)

In [45]: df
Out[45]: 
   y  gdp  cap
0  1    3    5
1  2    7    9
2  8    4    2
3  3    7    7
4  6  NaN    7

In [46]: df[:-1]                                                                                                                                                                                                                                                                                                               
Out[46]: 
   y  gdp  cap
0  1    3    5
1  2    7    9
2  8    4    2
3  3    7    7

这篇关于将 pandas 数据框中的列上移一格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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