Pandas Shift函数(错位相加减)

Pandas Shift函数基础

官方帮助文档如下:

>>> import pandas
>>> help(pandas.DataFrame.shift)
Help on function shift in module pandas.core.frame:
  
shift(self, periods=1, freq=None, axis=0)
 Shift index by desired number of periods with an optional time freq
  
 Parameters
 ----------
 periods : int
 Number of periods to move, can be positive or negative
 freq : DateOffset, timedelta, or time rule string, optional
 Increment to use from the tseries module or time rule (e.g. 'EOM').
 See Notes.
 axis : {
   0 or 'index', 1 or 'columns'}
  
 Notes
 -----
 If freq is specified then the index values are shifted but the data
 is not realigned. That is, use freq if you would like to extend the
 index when shifting and preserve the original data.
  
 Returns
 -------
 shifted : DataFrame

参数解释:

  • period:表示移动的幅度,可以是正数,也可以是负数,默认值是1,1就表示移动一次,注意这里移动的都是数据,而索引是不移动的,移动之后没有对应值的,就赋值为NaN。
  • freq: DateOffset, timedelta, or time rule string,可选参数,默认值为None,只适用于时间序列,如果这个参数存在,那么会按照参数值移动时间索引,而数据值没有发生变化。
  • axis: {0, 1, ‘index’, ‘columns’},表示移动的方向,如果是0或者’index’表示上下移动,如果是1或者’columns’,则会左右移动。
    先来看一下一些简单的示例

1、非时间索引下period的设置

假设存在一个DataFrame数据df:

index value1
A 0
B 1
C 2
D 3

如果执行以下代码 df.shift() 就会变成如下:

index value1
A NaN
B 0
C 1
D 2
  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值