7.2 时间序列的创建和转换


文档摘要

7.2 时间序列的创建和转换 Pandas 时间序列数据处理:7.2 时间序列的创建和转换 Pandas 提供了强大的时间序列处理功能。本节将深入探讨如何创建和转换时间序列数据,这是进行时间序列分析的基础。 7.2.1 创建时间序列 Pandas 提供了多种方法来创建时间序列数据,主要涉及 、 和 等对象。 1. 使用 创建单个时间戳 表示单个时间点。可以从字符串、整数、浮点数等多种类型创建 对象。 2. 使用 创建时间段 表示一个时间段,例如一天、一个月或一年。 3. 使用 创建时间序列 是 Pandas 中最常用的时间序列类型,它是一个时间戳的索引。 : 生成固定频率的日期序列。 : 生成固定频率的时间段序列。 : 将各种输入转换为日期时间对象。 4.

7.2 时间序列的创建和转换

Pandas 时间序列数据处理:7.2 时间序列的创建和转换

Pandas 提供了强大的时间序列处理功能。本节将深入探讨如何创建和转换时间序列数据,这是进行时间序列分析的基础。

7.2.1 创建时间序列

Pandas 提供了多种方法来创建时间序列数据,主要涉及 pd.Timestamppd.Periodpd.DatetimeIndex 等对象。

1. 使用 pd.Timestamp 创建单个时间戳

pd.Timestamp 表示单个时间点。可以从字符串、整数、浮点数等多种类型创建 pd.Timestamp 对象。

import pandas as pd # 从字符串创建 ts = pd.Timestamp('2023-10-27') print(ts) # 输出: 2023-10-27 00:00:00 print(type(ts)) # 输出: <class 'pandas._libs.tslibs.timestamps.Timestamp'> ts = pd.Timestamp('2023-10-27 10:30:00') print(ts) # 输出: 2023-10-27 10:30:00 # 从datetime对象创建 import datetime dt = datetime.datetime(2023, 10, 27, 12, 0, 0) ts = pd.Timestamp(dt) print(ts) # 输出: 2023-10-27 12:00:00 # 指定时区 ts = pd.Timestamp('2023-10-27 10:30:00', tz='Asia/Shanghai') print(ts) # 输出: 2023-10-27 10:30:00+08:00

2. 使用 pd.Period 创建时间段

pd.Period 表示一个时间段,例如一天、一个月或一年。

# 创建一个表示 2023 年 10 月的 Period 对象 period = pd.Period('2023-10') print(period) # 输出: 2023-10 print(type(period)) # 输出: <class 'pandas._libs.tslibs.period.Period'> # 创建一个表示 2023 年 10 月 27 日的 Period 对象 period = pd.Period('2023-10-27', freq='D') print(period) # 输出: 2023-10-27 # Period 的算术运算 period_next = period + 1 print(period_next) # 输出: 2023-10-28

3. 使用 pd.DatetimeIndex 创建时间序列

pd.DatetimeIndex 是 Pandas 中最常用的时间序列类型,它是一个时间戳的索引。

  • pd.date_range(): 生成固定频率的日期序列。
# 生成从 2023-10-01 开始,长度为 10 天的日期序列 date_index = pd.date_range('2023-10-01', periods=10) print(date_index) # 输出: # DatetimeIndex(['2023-10-01', '2023-10-02', '2023-10-03', '2023-10-04', # '2023-10-05', '2023-10-06', '2023-10-07', '2023-10-08', # '2023-10-09', '2023-10-10'], # dtype='datetime64[ns]', freq='D') # 指定频率为小时 date_index = pd.date_range('2023-10-27', periods=24, freq='H') print(date_index) # 输出: # DatetimeIndex(['2023-10-27 00:00:00', '2023-10-27 01:00:00', # '2023-10-27 02:00:00', '2023-10-27 03:00:00', # '2023-10-27 04:00:00', '2023-10-27 05:00:00', # '2023-10-27 06:00:00', '2023-10-27 07:00:00', # '2023-10-27 08:00:00', '2023-10-27 09:00:00', # '2023-10-27 10:00:00', '2023-10-27 11:00:00', # '2023-10-27 12:00:00', '2023-10-27 13:00:00', # '2023-10-27 14:00:00', '2023-10-27 15:00:00', # '2023-10-27 16:00:00', '2023-10-27 17:00:00', # '2023-10-27 18:00:00', '2023-10-27 19:00:00', # '2023-10-27 20:00:00', '2023-10-27 21:00:00', # '2023-10-27 22:00:00', '2023-10-27 23:00:00'], # dtype='datetime64[ns]', freq='H')
  • pd.period_range(): 生成固定频率的时间段序列。
# 生成从 2023-10 开始,长度为 12 个月的 Period 序列 period_index = pd.period_range('2023-10', periods=12, freq='M') print(period_index) # 输出: # PeriodIndex(['2023-10', '2023-11', '2023-12', '2024-01', '2024-02', '2024-03', # '2024-04', '2024-05', '2024-06', '2024-07', '2024-08', '2024-09'], # dtype='period[M]')
  • pd.to_datetime(): 将各种输入转换为日期时间对象。
# 将字符串列表转换为 DatetimeIndex dates = ['2023-10-27', '2023-10-28', '2023-10-29'] date_index = pd.to_datetime(dates) print(date_index) # 输出: # DatetimeIndex(['2023-10-27', '2023-10-28', '2023-10-29'], dtype='datetime64[ns]', freq=None) # 处理错误值 dates_with_error = ['2023-10-27', 'invalid date', '2023-10-29'] date_index = pd.to_datetime(dates_with_error, errors='coerce') print(date_index) # 输出: # DatetimeIndex(['2023-10-27', 'NaT', '2023-10-29'], dtype='datetime64[ns]', freq=None)

4. 使用 pd.Series 创建时间序列

可以将 DatetimeIndexPeriodIndex 作为 pd.Series 的索引,创建时间序列。

import numpy as np # 使用 DatetimeIndex 创建 Series date_index = pd.date_range('2023-10-01', periods=10) data = np.random.randn(10) ts_series = pd.Series(data, index=date_index) print(ts_series) # 使用 PeriodIndex 创建 Series period_index = pd.period_range('2023-01', periods=12, freq='M') data = np.random.randn(12) period_series = pd.Series(data, index=period_index) print(period_series)

7.2.2 时间序列的转换

创建时间序列后,可能需要进行转换以满足不同的分析需求。

1. 转换为不同的频率

  • resample(): 将时间序列数据重采样到另一个频率。这是时间序列分析中最常用的转换操作之一。
# 创建一个以天为频率的时间序列 date_index = pd.date_range('2023-10-01', periods=30) data = np.random.randn(30) ts_series = pd.Series(data, index=date_index) # 将频率转换为周,并计算每周的平均值 weekly_average = ts_series.resample('W').mean() print(weekly_average) # 将频率转换为月,并计算每月的总和 monthly_sum = ts_series.resample('M').sum() print(monthly_sum)
  • asfreq(): 将时间序列转换为指定的频率。与 resample() 不同,asfreq() 不执行聚合操作,而是根据指定的频率选择或插入数据。
# 创建一个以天为频率的时间序列 date_index = pd.date_range('2023-10-01', periods=10) data = np.random.randn(10) ts_series = pd.Series(data, index=date_index) # 转换为每周频率 weekly_series = ts_series.asfreq('W') print(weekly_series) # 会显示每个周日的数值,如果该日期不存在,则显示 NaN

2. 时区转换

Pandas 可以处理带有时区信息的时间序列。

  • tz_localize(): 将时间序列本地化到指定的时区。

  • tz_convert(): 将时间序列从一个时区转换为另一个时区。

# 创建一个不带时区的时间序列 date_index = pd.date_range('2023-10-27 08:00:00', periods=3, freq='H') ts_series = pd.Series(np.random.randn(3), index=date_index) print(ts_series) # 本地化到 'Asia/Shanghai' 时区 ts_series_localized = ts_series.tz_localize('Asia/Shanghai') print(ts_series_localized) # 转换为 'UTC' 时区 ts_series_utc = ts_series_localized.tz_convert('UTC') print(ts_series_utc)

3. 转换为 PeriodIndex 和 DatetimeIndex

  • to_period(): 将 DatetimeIndex 转换为 PeriodIndex

  • to_timestamp(): 将 PeriodIndex 转换为 DatetimeIndex

# 创建一个 DatetimeIndex date_index = pd.date_range('2023-10-01', periods=12, freq='M') # 转换为 PeriodIndex period_index = date_index.to_period() print(period_index) # 转换为 DatetimeIndex datetime_index = period_index.to_timestamp() print(datetime_index)

7.2.3 时间序列创建和转换的流程图

7.2.4 总结

本节介绍了 Pandas 中时间序列的创建和转换方法。掌握这些方法对于进行时间序列分析至关重要。通过灵活运用 pd.Timestamppd.Periodpd.DatetimeIndex 和相关的转换函数,可以有效地处理各种时间序列数据,为后续的分析和建模奠定基础。在实际应用中,需要根据具体的需求选择合适的创建和转换方式。例如,金融数据通常需要处理时区信息,而分析季节性趋势可能需要进行频率转换。


作者与出处
原作者: 灏天文库
来源:灏天文库
整理: 灏天文库整理
由灏天文库平台收录,内容或由平台用户上传,仅供学习交流
发布者: 作者: 灏天文库 转发
评论区 (0)
U