如何在Python中用滚动平均法制作时间序列图
时间序列图用于观察数据集在一段时期内的各种趋势。在这样的问题中,数据是按时间排序的,并且会因数据集中考虑的时间单位(日、月、秒、小时等)而波动。当绘制时间序列数据时,这些波动可能会妨碍我们清楚地获得关于图表中的高峰和低谷的洞察力。因此,为了清楚地从数据中获得价值,我们使用滚动平均概念来绘制时间序列图。
滚动平均数或移动平均数是过去’n’个数值的简单平均值。它可以帮助我们找到原本难以发现的趋势。此外,它们还可以用来确定长期趋势。你可以简单地通过将以前的’n’个数值相加并除以’n’本身来计算滚动平均值。但对于这一点,滚动平均值的前(n-1)个值将是南。
在这篇文章中,我们将学习如何在Python中使用Pandas和Seaborn库制作滚动平均的时间序列图。下面是使用pandas计算滚动平均数的语法。
语法:
pandas.DataFrame.rolling(n).mean()
我们将使用 “每日女性出生数据集”。这个数据集描述了1959年加利福尼亚每天的女性出生人数。从1959年1月1日到1959年12月31日有365个观测值。你可以从这个链接下载该数据集。
一步一步实现:
第1步:导入库。
# import the libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
第2步:导入数据集
# import the dataset
data = pd.read_csv( "https://raw.githubusercontent.com/jbrownlee/ \
Datasets/master/daily-total-female-births.csv")
#view the dataset
display( data.head())
输出:
第3步:使用seaborn.lineeplot()绘制一个简单的时间序列图。
# set figure size
plt.figure( figsize = ( 12, 5))
# plot a simple time series plot
# using seaborn.lineplot()
sns.lineplot( x = 'Date',
y = 'Births',
data = data,
label = 'DailyBirths')
plt.xlabel( 'Months of the year 1959')
# setting customized ticklabels for x axis
pos = [ '1959-01-01', '1959-02-01', '1959-03-01', '1959-04-01',
'1959-05-01', '1959-06-01', '1959-07-01', '1959-08-01',
'1959-09-01', '1959-10-01', '1959-11-01', '1959-12-01']
lab = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June',
'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
plt.xticks( pos, lab)
plt.ylabel('Female Births')
输出:

我们可以注意到,由于数据波动很大,很难从上述图表中获得知识。因此,让我们再次绘制它,但这次使用滚动平均概念。
**第四步:使用pandas.DataFrame.rolling.mean()计算滚动平均值。
对于滚动平均,我们必须采取一定的窗口大小。在这里,我们采取了窗口大小=7,即7天或1周的滚动平均。
# computing a 7 day rolling average
data[ '7day_rolling_avg' ] = data.Births.rolling( 7).mean()
# viewing the dataset
Display(data.head(10))
输出:
我们可以观察到,’7天_滚动_avg’列的前6个值是NaN值。这是因为这6个值没有足够的数据来计算7天的滚动平均值。因此,在图表中,对于前6个值,也不会有任何数值被绘制出来。
步骤5:使用步骤4中计算的滚动平均数制作时间序列图
# set figure size
plt.figure( figsize = ( 12, 5))
# plot a simple time series plot
# using seaborn.lineplot()
sns.lineplot( x = 'Date',
y = 'Births',
data = data,
label = 'DailyBirths')
# plot using rolling average
sns.lineplot( x = 'Date',
y = '7day_rolling_avg',
data = data,
label = 'Rollingavg')
plt.xlabel('Months of the year 1959')
# setting customized ticklabels for x axis
pos = [ '1959-01-01', '1959-02-01', '1959-03-01', '1959-04-01',
'1959-05-01', '1959-06-01', '1959-07-01', '1959-08-01',
'1959-09-01', '1959-10-01', '1959-11-01', '1959-12-01']
lab = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June',
'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
plt.xticks( pos, lab)
plt.ylabel('Female Births')
输出:

通过上图我们可以清楚地看到,滚动平均数使女性出生人数变得平滑,我们可以更明显地注意到峰值。
极客教程