Pandas中时间序列的移动—shift()函数方法

         移动是指沿着时间轴方向将数据进行前移或后移。Pandas对象中提供了一个shift()方法,用来前移或后移数据,但索引保持不变。shift()方法语法格式如下:shift(periods=1,freq=None,axis=0)

部分参数含义如下:

  1. periods:表示移动的幅度,可以为正数,也可以为负数,默认值是1,代表移动一次。
  2. freq:如果这个参数存在,那么会按照参数值移动时间戳索引,而数据值没有发生变化

接下来通过代码演示:

Pandas中时间序列的移动—shift()函数方法_第1张图片

import pandas as pd                     #时间序列的移动 shift方法
import numpy as np
date_index=pd.date_range('2020/12/2',periods=5)
time_ser=pd.Series(np.arange(5)+1,index=date_index)
time_ser

         例子1 periods参数的用法:

Pandas中时间序列的移动—shift()函数方法_第2张图片

import pandas as pd                     #时间序列的移动 shift方法
import numpy as np
date_index=pd.date_range('2020/12/2',periods=5)
time_ser=pd.Series(np.arange(5)+1,index=date_index)
time_ser

time_ser.shift(periods=1)          #正数向后移动,数据向下移动,向未来日期移动,没有数据的日期变成 NaN

time_ser.shift(periods=-1)          #负数向前移动,数据向上移动,向过去日期移动,没有数据的日期变成 NaN

         例子2 freq参数的用法:

Pandas中时间序列的移动—shift()函数方法_第3张图片

import pandas as pd
import numpy as np
date_index=pd.date_range('2020/12/2',periods=5)
time_ser=pd.Series(np.arange(5)+1,index=date_index)
time_ser

time_ser.shift(freq='2D')

time_ser.shift(1,freq='2D')

作者:KJ.JK
本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。
文章对你有所帮助的话,欢迎给个赞或者 star 呀,你的支持是对作者最大的鼓励,不足之处可以在评论区多多指正,交流学习呀

你可能感兴趣的:(数据分析中的pandas,python,pandas,shift,数据可视化,数据分析)