Pandas 按时间间隔的滚动平均值

Pandas 按时间间隔的滚动平均值

在这篇文章中,我们将研究如何使用Pandas在Python中按时间间隔计算一个数据框架的滚动平均值。

Pandas dataframe.rolling()是一个帮助我们在一个滚动窗口上进行计算的函数。换句话说,我们采取一个固定大小的窗口并对其进行一些数学计算。

语法: DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0)

参数 :

  • window : 窗口的大小。这就是我们要为每个窗口的计算采取多少个观测值。
  • min_periods :在一个窗口中需要有一个值的最小观察数(否则结果为NA)。
  • center : 用来设置窗口中心的标签。
  • win_type :它用于设置窗口类型。
  • on:我们要计算滚动平均值的数据框架的日期列。
  • axis:整数或字符串,默认为0

一步一步实现

第1步:导入库

# import pandas as pd
import pandas as pd
Python

第2步:导入数据

# importing Data
tesla_df = pd.read_csv('Tesla_Stock.csv', index_col='Date', 
                       parse_dates=True)
  
# printing the dataFrame
tesla_df.head(10)
Python

输出 :

Pandas - 按时间间隔的滚动平均值

我们将计算DataFrame中 “Close “列的滚动平均值。

第3步:计算滚动平均值

# Updating the dataFrame with just the 
# column 'Close' as others columns are 
# of no use right now we have used .to_frame
# which converts Series to a DataFrame.
tesla_df = tesla_df['Close'].to_frame()
  
  
# calculating Rolling mean and storing it 
# into a new column of existing dataFrame
# we have set the window as 30 and rest all
# parameters are set to default.
tesla_df['MA30'] = tesla_df['Close'].rolling(30).mean()
  
# Rolling mean is also called as Moving Average ,
# hence we have used the notation MA
# and MA30 is the moving average (rolling mean) 
# of 30 days
  
# printing dataframe
tesla_df
Python

输出:

Pandas - 按时间间隔的滚动平均值

MA30列的前29行将有一个NULL值,第一个非NULL值将在第30行。现在我们将计算滚动平均值,窗口为200。

# calculating Rolling mean and storing it into
# a new column of existing dataFrame we have set
# the window as 200 and rest all parameters are 
# set to default.
tesla_df['MA200'] = tesla_df['Close'].rolling(200).mean()
  
# Rolling mean is also called as Moving Average, hence
# we have used the notation MA and MA200 is the moving
# average (rolling mean) of 200 days
  
# printing dataframe
tesla_df
Python

输出 :

Pandas - 按时间间隔的滚动平均值

对于’MA200’来说,第一个非NULL将在第200行。现在让我们绘制’MA30’、’MA200’和’Close’,以获得更好的视觉效果

第4步:制图

# importing matplotlib module
import matplotlib.pyplot as plt
plt.style.use('default')
  
# %matplotlib inline: only draw static
# images in the notebook
%matplotlib inline
  
tesla_df[['Close', 'MA30', 'MA200']].plot(
  label='tesla', figsize=(16, 8))
Python

输出:

Pandas - 按时间间隔的滚动平均值

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册