Pandas Shift函数的基础入门学习笔记
作者:标点符 发布时间:2023-02-16 20:46:12
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
该函数主要的功能就是使数据框中的数据移动,若freq=None时,根据axis的设置,行索引数据保持不变,列索引数据可以在行上上下移动或在列上左右移动;若行索引为时间序列,则可以设置freq参数,根据periods和freq参数值组合,使行索引每次发生periods*freq偏移量滚动,列索引数据不会移动。
参数详解:
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
执行 df.shift(2) 就会得到:
index value1
A NaN
B NaN
C 0
D 1
执行 df.shift(-1) 会得到:
index value1
A 1
B 2
C 3
D NaN
注意,shift移动的是整个数据,如果df有如下多列数据:
AA BB CC DD
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
执行 df.shift(2) 的数据为:
AA BB CC DD
a NaN NaN NaN NaN
b NaN NaN NaN NaN
c 0.0 1.0 2.0 3.0
d 4.0 5.0 6.0 7.0
如果只想移动df中的某一列数据,则需要这样操作: df['DD']= df['DD'].shift(1)
执行后的数据为:
AA BB CC DD
a 0 1 2 NaN
b 4 5 6 NaN
c 8 9 10 11
d 12 13 14 15
2、时间索引下freq 参数设置
假设存在如下DataFrame的df:
df = pd.DataFrame(np.arange(16).reshape(4,4),columns=['AA','BB','CC','DD'],index =pd.date_range('2012-06-01','2012-06-04'))
AA BB CC DD
2012-06-01 0 1 2 3
2012-06-02 4 5 6 7
2012-06-03 8 9 10 11
2012-06-04 12 13 14 15
执行 df.shift(freq=datetime.timedelta(1)) 后:
AA BB CC DD
2012-06-02 0 1 2 3
2012-06-03 4 5 6 7
2012-06-04 8 9 10 11
2012-06-05 12 13 14 15
执行 df.shift(freq=datetime.timedelta(-2)) 后:
AA BB CC DD
2012-05-30 0 1 2 3
2012-05-31 4 5 6 7
2012-06-01 8 9 10 11
2012-06-02 12 13 14 15
可以看到索引直接变了。
3、axis轴向设置
df = pd.DataFrame(np.arange(16).reshape(4,4),columns=['AA','BB','CC','DD'],index =['a','b','c','d'])
df
Out[1]:
AA BB CC DD
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
#当period为正时,默认是axis = 0轴的设定,向下移动
df.shift(2)
Out[2]:
AA BB CC DD
a NaN NaN NaN NaN
b NaN NaN NaN NaN
c 0.0 1.0 2.0 3.0
d 4.0 5.0 6.0 7.0
#当axis=1,沿水平方向进行移动,正数向右移,负数向左移
df.shift(2,axis = 1)
Out[3]:
AA BB CC DD
a NaN NaN 0.0 1.0
b NaN NaN 4.0 5.0
c NaN NaN 8.0 9.0
d NaN NaN 12.0 13.0
#当period为负时,默认是axis = 0轴的设定,向上移动
df.shift(-1)
Out[4]:
AA BB CC DD
a 4.0 5.0 6.0 7.0
b 8.0 9.0 10.0 11.0
c 12.0 13.0 14.0 15.0
d NaN NaN NaN NaN
pandas 中上下两行相减(隔行相减) -- shift函数的使用
最近使用pandas处理数据,需求是想相邻两行上下相减,查API发现shift函数,很灵活,。你也可以隔任意行相减。
p['xx_1'] = p["xx"].shift(1)
上面得到的就是xx字段向下移动一行的结果,和之前相比向下移动一行,你可以设置为任意行,也可是向上向下
p['xx'] - p["xx_1"]
这就是前后两行的差值,很方便,Pandas很强大
来源:https://www.biaodianfu.com/pandas-shift.html
猜你喜欢
- 抛出问题:求一数组如 l = [0, 1, 2, 3, -4, 5, -6],求该数组的最大连续子数组的和 如结果为[0,1,2,3,-4,
- 在这里我们介绍两个拼接数组的方法:np.vstack():在竖直方向上堆叠np.hstack():在水平方向上平铺import numpy
- 这篇文章主要介绍了python集合删除多种方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可
- 步骤1、安装Jupyterpip install jupyter2、 新建一个IPython文件3、在Terminal里启动Jupyter
- 修复Access数据库,我们一般使用微软Office 97中带的Access 97对数据库进行修复和整理。Access数据库被损坏分以下几种
- Microsoft SQL Server™ 2000 提供了两种主要机制来强制业务规则和数据完整性:约束和触发器。触发器是一种特殊类型的存储
- 如下所示:>>> import numpy as np>>> a = np.array([[1, 2,
- os.Rename()这个函数的原型是func Rename(oldname, newname string) error,输入的是旧文件名
- 这段时间应老师的要求,给实验室写了一个基于 PyQt5 的小工具。然而源码发过去人家还不要,一定要打包成可执行软件。那就打包呗,刚好以前对
- 由于笔者最近在做一个跨数据库操作的测试,开始做IBatisNet (IBatis.DataMapper.1.6.2/IBatis.DataA
- 微信小程序实现图片轮播及文件上传刚刚接触微信小程序,看着网上的资源写了个小例子,本地图片轮播以及图片上传。图片轮播:index.
- 本文实例讲述了ThinkPHP中自定义错误页面和提示页面的方法。分享给大家供大家参考。具体实现方法如下:在ThinkPHP中有两个方法时提示
- 最近媳妇工作上遇到一个重复性劳动,excel表格查重,重复的标记起来,问我能不能写个程序让它自动查重标记必须安排第一次正儿八经写python
- python格式化字符串有%和{}两种 字符串格式控制符.字符串输入数据格式类型(%格式操作符号)%%百分号标记#就是输出一个%%c字符及其
- 实测mysqld –skip-grant-tables这样的命令行,在mysql8中无法成功启动,而且测试了该参数放在ini文件里面也同样无
- 使用教程(注意细看总结部分,写了几点,希望有所帮助):1、安装插件:npm install vue-quill-editor2、安装插件依赖
- 今天整理之前写的代码,发现在做数模期间写的用python实现的遗传算法,感觉还是挺有意思的,就拿出来分享一下。首先遗传算法是一种优化算法,通
- MVC代表: 模型-视图-控制器 。MVC是一个架构良好并且易于测试和易于维护的开发模式。基于MVC模式的应用程序包含:· Models:
- 为什么我把自己机子上的数据库备份文件往另一台机子上还原不成功?可能是你在Restore的对话框中选项不正确。Restore 有三个选项,分别
- 2.1数据的爬取代码:import pandas as pddata=pd.read_csv("example_data.csv&