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

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

    相关文章

    Python使用FastAPI实现大文件分片上传与断点续传功能

    《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

    Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

    《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

    基于Java和FFmpeg实现视频压缩和剪辑功能

    《基于Java和FFmpeg实现视频压缩和剪辑功能》在视频处理开发中,压缩和剪辑是常见的需求,本文将介绍如何使用Java结合FFmpeg实现视频压缩和剪辑功能,同时去除数据库操作,仅专注于视频处理,需... 目录引言1. 环境准备1.1 项目依赖1.2 安装 FFmpeg2. 视频压缩功能实现2.1 主要功

    使用Python实现无损放大图片功能

    《使用Python实现无损放大图片功能》本文介绍了如何使用Python的Pillow库进行无损图片放大,区分了JPEG和PNG格式在放大过程中的特点,并给出了示例代码,JPEG格式可能受压缩影响,需先... 目录一、什么是无损放大?二、实现方法步骤1:读取图片步骤2:无损放大图片步骤3:保存图片三、示php

    深度解析Python yfinance的核心功能和高级用法

    《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?

    Python脚本轻松实现检测麦克风功能

    《Python脚本轻松实现检测麦克风功能》在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的... 目录轻松检测麦克风功能脚本介绍一、python环境准备二、代码解析三、使用方法四、知识扩展轻松检测麦

    Java实现TXT文件导入功能的详细步骤

    《Java实现TXT文件导入功能的详细步骤》在实际开发中,很多应用场景需要将用户上传的TXT文件进行解析,并将文件中的数据导入到数据库或其他存储系统中,本文将演示如何用Java实现一个基本的TXT文件... 目录前言1. 项目需求分析2. 示例文件格式3. 实现步骤3.1. 准备数据库(假设使用 mysql

    Springboot项目登录校验功能实现

    《Springboot项目登录校验功能实现》本文介绍了Web登录校验的重要性,对比了Cookie、Session和JWT三种会话技术,分析其优缺点,并讲解了过滤器与拦截器的统一拦截方案,推荐使用JWT... 目录引言一、登录校验的基本概念二、HTTP协议的无状态性三、会话跟android踪技术1. Cook

    基于Spring Boot 的小区人脸识别与出入记录管理系统功能

    《基于SpringBoot的小区人脸识别与出入记录管理系统功能》文章介绍基于SpringBoot框架与百度AI人脸识别API的小区出入管理系统,实现自动识别、记录及查询功能,涵盖技术选型、数据模型... 目录系统功能概述技术栈选择核心依赖配置数据模型设计出入记录实体类出入记录查询表单出入记录 VO 类(用于

    Qt中实现多线程导出数据功能的四种方式小结

    《Qt中实现多线程导出数据功能的四种方式小结》在以往的项目开发中,在很多地方用到了多线程,本文将记录下在Qt开发中用到的多线程技术实现方法,以导出指定范围的数字到txt文件为例,展示多线程不同的实现方... 目录前言导出文件的示例工具类QThreadQObject的moveToThread方法实现多线程QC