不要错过熊猫滚动窗口功能

2023-12-06 19:10

本文主要是介绍不要错过熊猫滚动窗口功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Python (PYTHON)

Window calculations can add a lot of depth to your data analysis.

窗口计算可以为您的数据分析增加很多深度。

The Pandas library lets you perform many different built-in aggregate calculations, define your functions and apply them across a DataFrame, and even work with multiple columns in a DataFrame simultaneously. A feature in Pandas you might not have heard of before is the built-in Window functions.

通过Pandas库,您可以执行许多不同的内置聚合计算,定义函数并在DataFrame中应用它们,甚至可以同时处理DataFrame中的多个列。 内置的Window 功能是您以前可能从未听说过的Pandas 功能

Window functions are useful because you can perform many different kinds of operations on subsets of your data. Rolling window functions specifically let you calculate new values over each row in a DataFrame. This might sound a bit abstract, so let’s just dive into the explanations and examples.

窗口函数很有用,因为您可以对数据的子集执行许多不同种类的操作。 滚动窗口功能特别允许您计算DataFrame中每一行的新值。 这听起来可能有点抽象,所以让我们深入了解一下解释和示例。

Examples in this piece will use some old Tesla stock price data from Yahoo Finance. Feel free to run the code below if you want to follow along. For more information on pd.read_html and df.sort_values, check out the links at the end of this piece.

本文中的示例将使用Yahoo Finance的一些旧特斯拉股价数据。 如果您想继续,请随时运行以下代码。 有关pd.read_htmldf.sort_values更多信息,请查看本文末尾的链接。

import pandas as pddf = pd.read_html("https://finance.yahoo.com/quote/TSLA/history?period1=1546300800&period2=1550275200&interval=1d&filter=history&frequency=1d")[0]
df = df.head(11).sort_values(by='Date')
df = df.astype({"Open":'float',
"High":'float',
"Low":'float',
"Close*":'float',
"Adj Close**":'float',
"Volume":'float'})
df['Gain'] = df['Close*'] - df['Open']
Image for post
Yahoo Finance Yahoo Finance的修改后的特斯拉股票数据样本

在Pandas DataFrame中滚动功能 (Rolling Functions in a Pandas DataFrame)

So what is a rolling window calculation?

那么什么是滚动窗口计算?

You’ll typically use rolling calculations when you work with time-series data. Again, a window is a subset of rows that you perform a window calculation on. After you’ve defined a window, you can perform operations like calculating running totals, moving averages, ranks, and much more!

处理时间序列数据时,通常会使用滚动计算。 同样, 窗口是执行窗口计算所依据的行的子集。 定义窗口后,您可以执行诸如计算运行总计,移动平均值,排名等操作!

Let’s clear this up with some examples.

让我们用一些例子来澄清这一点。

1.窗口滚动平均值(移动平均值) (1. Window Rolling Mean (Moving Average))

The moving average calculation creates an updated average value for each row based on the window we specify. The calculation is also called a “rolling mean” because it’s calculating an average of values within a specified range for each row as you go along the DataFrame.

移动平均计算基于我们指定的窗口为每一行创建一个更新的平均值。 该计算也称为“滚动平均值”,因为它是在沿DataFrame进行计算时,为每一行计算指定范围内的平均值。

That sounds a bit abstract, so let’s calculate the rolling mean for the “Close” column price over time. To do so, we’ll run the following code:

这听起来有点抽象,所以让我们计算“关闭”列价格随时间的滚动平均值。 为此,我们将运行以下代码:

df['Rolling Close Average'] = df['Close*'].rolling(2).mean()
Image for post
Rolling average results
滚动平均结果

We’re creating a new column “Rolling Close Average” which takes the moving average of the close price within a window. To do this, we simply write .rolling(2).mean(), where we specify a window of “2” and calculate the mean for every window along the DataFrame. Each row gets a “Rolling Close Average” equal to its “Close*” value plus the previous row’s “Close*” divided by 2 (the window). In essence, it’s Moving Avg = ([t] + [t-1]) / 2.

我们正在创建一个新列“滚动收盘平均线”,该列采用窗口内收盘价的移动平均线。 为此,我们只需编写.rolling(2).mean() ,在其中我们将窗口指定为“ 2”并计算沿DataFrame的每个窗口的均值。 每行将获得一个“滚动平均收支”,该值等于其“关闭*”值加上前一行的“关闭*”除以2(窗口)。 本质上,它是Moving Avg = ([t] + [t-1]) / 2

In practice, this means the first calculated value (62.44 + 62.58) / 2 = 62.51, which is the “Rolling Close Average” value for February 4. There is no rolling mean for the first row in the DataFrame, because there is no available [t-1] or prior period “Close*” value to use in the calculation, which is why Pandas fills it with a NaN value.

实际上,这意味着第一个计算值(62.44 + 62.58) / 2 = 62.51 ,它是2月4日的“滚动平均收盘(62.44 + 62.58) / 2 = 62.51 ”值。由于没有可用的数据帧,因此第一行没有滚动平均值。 [t-1]或上一个期间的“ Close *”值要在计算中使用,这就是Pandas用NaN值填充它的原因。

2.窗户滚动标准偏差 (2. Window Rolling Standard Deviation)

To further see the difference between a regular calculation and a rolling calculation, let’s check out the rolling standard deviation of the “Open” price. To do so, we’ll run the following code:

为了进一步了解常规计算和滚动计算之间的区别,让我们检查一下“开放”价格的滚动标准偏差。 为此,我们将运行以下代码:

df['Open Standard Deviation'] = df['Open'].std()
df['Rolling Open Standard Deviation'] = df['Open'].rolling(2).std()
Image for post
Rolling standard deviation results
滚动标准偏差结果

I also included a new column “Open Standard Deviation” for the standard deviation that simply calculates the standard deviation for the whole “Open” column. Beside it, you’ll see the “Rolling Open Standard Deviation” column, in which I’ve defined a window of 2 and calculated the standard deviation for each row.

我还为标准偏差添加了一个新列“开放标准偏差”,该列仅计算整个“开放”列的标准偏差。 在它旁边,您将看到“滚动打开标准偏差”列,其中我定义了一个2的窗口并计算了每一行的标准偏差。

Just as with the previous example, the first non-null value is at the second row of the DataFrame, because that’s the first row that has both [t] and [t-1]. You can see how the moving standard deviation varies as you move down the table, which can be useful to track volatility over time.

与前面的示例一样,第一个非null值位于DataFrame的第二行,因为这是同时具有[t ]和[t-1]的第一行。 您可以看到随着向下移动表格的移动标准偏差的变化,这对于跟踪一段时间内的波动率很有用。

Pandas uses N-1 degrees of freedom when calculating the standard deviation. You can pass an optional argument to ddof, which in the std function is set to “1” by default.

熊猫在计算标准偏差时使用N-1个自由度。 您可以将可选参数传递给ddof ,该参数在std函数中默认设置为“ 1”。

3.窗口滚动总和 (3. Window Rolling Sum)

As a final example, let’s calculate the rolling sum for the “Volume” column. To do so, we run the following code:

作为最后一个示例,让我们计算“体积”列的滚动总和。 为此,我们运行以下代码:

df['Rolling Volume Sum'] = df['Volume'].rolling(3).sum()
Image for post
Rolling sum results
累计结果

We’ve defined a window of “3”, so the first calculated value appears on the third row. The sum calculation then “rolls” over every row, so that you can track the sum of the current row and the two prior row’s values over time.

我们定义了一个窗口“ 3”,因此第一个计算出的值出现在第三行上。 然后,总和计算将“滚动”到每一行,以便您可以随时间跟踪当前行和前两个行的值之和。

It’s important to emphasize here that these rolling (moving) calculations should not be confused with running calculations. Rolling calculations, as you can see int he diagram above, have a moving window. So with our moving sum, the calculated value for February 6 (the fourth row) does not include the value for February 1 (the first row), because the specified window (3) does not go that far back. In contrast, a running calculation would take continually add each row value to a running total value across the whole DataFrame. You can check out the cumsum function for that.

在此必须强调的是,这些滚动 (移动)计算不应与运行计算混淆。 如上图所示,滚动计算有一个移动的窗口。 因此,使用我们的移动总和,2月6日(第四行)的计算值不包括2月1日(第一行)的值,因为指定的窗口(3)不会那么远。 相反,正在运行的计算将需要连续将每个行值添加到整个DataFrame的正在运行的总值中。 您可以cumsum查看cumsum函数。

I hope you found this very basic introduction to logical comparisons in Pandas using the wrappers useful. Remember to only compare data that can be compared (i.e. don’t try to compare a string to a float) and manually double-check the results to make sure your calculations are producing the intended results.

我希望您发现使用包装程序对熊猫进行逻辑比较非常基础的介绍很有用。 请记住,仅比较可比较的数据(即不要尝试将字符串与浮点数进行比较),并手动仔细检查结果以确保您的计算产生了预期的结果。

Go forth and compare!

继续比较吧!

More by me:
*
2 Easy Ways to Get Tables From a Website
*
4 Different Ways to Efficiently Sort a Pandas DataFrame
- Top 4 Repositories on GitHub to Learn Pandas
- How to Quickly Create and Unpack Lists with Pandas
- Learning to Forecast With Tableau in 5 Minutes Or Less

翻译自: https://towardsdatascience.com/dont-miss-out-on-rolling-window-functions-in-pandas-850b817131db


http://www.taodudu.cc/news/show-8380976.html

相关文章:

  • c++数据结构之线性表:间接寻址类模板的实现
  • 论did you 和 have you And are you
  • java script 经典之作
  • Checkpoint防火墙ClusterXL 故障之FIB Problem问题解决
  • AndroidStudio 启动Automotive模拟器失败
  • 使用VMWare安装Ubentu指南
  • logstash配置syslog外发
  • 网页制作必备之初级代码
  • linux之openssh协议
  • WebSocket之ServerEndPoint
  • 已发生的、正发生的和尚未发生的
  • 关于Color的三个问题
  • sql查询——查询排名为m~n的学生
  • 三星推QLED 8K电视 LG表示8K和OLED更配
  • 三星QLED彻底击败LG OLED电视,华为将加入QLED阵营
  • 三星发布QLED TV新品,用AI与IoT技术定义下一代电视 | 速递
  • 冷热交替的电视市场,QLED甩开了OLED一段路程
  • mysql dbuild_config_mysqld config
  • C语言学习随笔记之EOF用法
  • Dynamo For Revit: CurtainPanel 幕墙嵌板
  • IISWeb应用防火墙WAF
  • Java实现 蓝桥杯VIP 算法提高 前10名
  • freeotp 安装及使用过程
  • 安全工具-WAF网络防火墙探测工具(WAFw00f)安装
  • 一个让程序员撞了南墙才回头的8句话!(摘自互联网:出处不明)
  • 讲解C++中的深度优先搜索(DFS)
  • 信息学奥赛一本通 166:The Castle
  • python培训感想800字
  • 腾讯研究院发布《中国分享经济全景解读报告》
  • 知识付费的发展困境和发展趋势
  • 这篇关于不要错过熊猫滚动窗口功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



    http://www.chinasem.cn/article/462970

    相关文章

    PostgreSQL中rank()窗口函数实用指南与示例

    《PostgreSQL中rank()窗口函数实用指南与示例》在数据分析和数据库管理中,经常需要对数据进行排名操作,PostgreSQL提供了强大的窗口函数rank(),可以方便地对结果集中的行进行排名... 目录一、rank()函数简介二、基础示例:部门内员工薪资排名示例数据排名查询三、高级应用示例1. 每

    Qt使用QSqlDatabase连接MySQL实现增删改查功能

    《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

    mysql表操作与查询功能详解

    《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

    Golang如何用gorm实现分页的功能

    《Golang如何用gorm实现分页的功能》:本文主要介绍Golang如何用gorm实现分页的功能方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景go库下载初始化数据【1】建表【2】插入数据【3】查看数据4、代码示例【1】gorm结构体定义【2】分页结构体

    Java Web实现类似Excel表格锁定功能实战教程

    《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

    HTML5实现的移动端购物车自动结算功能示例代码

    《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

    基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

    《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

    springboot下载接口限速功能实现

    《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

    苹果macOS 26 Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色

    《苹果macOS26Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色》在整体系统设计方面,macOS26采用了全新的玻璃质感视觉风格,应用于Dock栏、应用图标以及桌面小部件等多个界面... 科技媒体 MACRumors 昨日(6 月 13 日)发布博文,报道称在 macOS 26 Tahoe 中

    Java使用HttpClient实现图片下载与本地保存功能

    《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.