codecamp

AI人工智能 Pandas

Pandas:处理、切片和从时间序列数据中提取统计信息

如果您需要处理时间序列数据,Pandas 是一个非常有用的工具。借助 Pandas,您可以执行以下操作:

  • 使用pd.date_range包创建日期范围
  • 使用pd.Series包为 Pandas 数据添加日期索引
  • 使用ts.resample包执行重采样
  • 更改频率

示例

以下示例展示了如何使用 Pandas 处理和切片时间序列数据。请注意,这里我们使用的是月度北极涛动数据,您可以从 monthly.ao.index.b50.current.ascii 下载并将其转换为文本格式供我们使用。

处理时间序列数据

要处理时间序列数据,您需要执行以下步骤:

第一步是导入以下包:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

接下来,定义一个函数,它将从输入文件中读取数据,如下面的代码所示:

def read_data(input_file):
    input_data = np.loadtxt(input_file, delimiter=None)

现在,将此数据转换为时间序列。为此,创建我们时间序列的日期范围。在这个示例中,我们将数据的频率设置为一个月。我们的文件包含从 1950 年 1 月开始的数据。

dates = pd.date_range('1950-01', periods=input_data.shape[0], freq='M')

在这一步中,我们借助 Pandas Series 创建时间序列数据,如下所示:

output = pd.Series(input_data[:, index], index=dates)
return output


if __name__ == '__main__':

输入输入文件的路径,如下所示:

input_file = "/Users/admin/AO.txt"

现在,将列转换为时间序列格式,如下所示:

timeseries = read_data(input_file)

最后,使用以下命令绘制并可视化数据:

plt.figure()
timeseries.plot()
plt.show()

您将观察到如下所示的图表:

切片时间序列数据

切片是指仅检索时间序列数据的一部分。作为示例的一部分,我们仅对 1980 年至 1990 年的数据进行切片。观察以下执行此任务的代码:

timeseries['1980':'1990'].plot()
<matplotlib.axes._subplots.AxesSubplot at 0xa0e4b00>
plt.show()

当您运行切片时间序列数据的代码时,您可以观察到如下所示的图表:

AI人工智能 安装有用的包
AI人工智能 从时间序列数据中提取统计信息
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

AI人工智能监督学习(回归)

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }