Skip to content

时间索引

Pandas 提供了强大的时间序列处理功能,时间索引是其中的核心概念。

创建时间索引

python
import pandas as pd

# 创建日期范围
dates = pd.date_range(start='2024-01-01', end='2024-01-10')
print(dates)

# 指定频率
dates = pd.date_range(start='2024-01-01', periods=10, freq='D')
print(dates)

# 创建DataFrame
df = pd.DataFrame({'值': range(10)}, index=dates)
print(df)

时间索引属性

python
dates = pd.date_range('2024-01-01', periods=5)
df = pd.DataFrame({'销售额': [100, 120, 110, 130, 140]}, index=dates)

# 访问时间属性
print(df.index.year)
print(df.index.month)
print(df.index.day)
print(df.index.dayofweek)
print(df.index.day_name())
print(df.index.is_month_end)

时间切片

python
# 按日期切片
print(df['2024-01-02':'2024-01-04'])

# 按月份切片
print(df['2024-01'])

# 使用loc
print(df.loc['2024-01-03'])

时间序列数据读取

python
# 读取时解析日期
df = pd.read_csv('data.csv', parse_dates=['日期列'])

# 设置日期为索引
df.set_index('日期列', inplace=True)

时间重采样

python
# 创建日频数据
dates = pd.date_range('2024-01-01', periods=30, freq='D')
df = pd.DataFrame({'值': range(30)}, index=dates)

# 降采样:日转周
weekly = df.resample('W').sum()
print(weekly)

# 降采样:日转月
monthly = df.resample('M').mean()
print(monthly)

# 升采样:日转小时
daily = df.resample('H').ffill()

移动窗口

python
# 创建数据
dates = pd.date_range('2024-01-01', periods=10)
df = pd.DataFrame({'值': [10, 15, 12, 18, 20, 15, 22, 25, 20, 28]}, index=dates)

# 移动平均
df['移动平均'] = df['值'].rolling(window=3).mean()

# 指数移动平均
df['指数移动平均'] = df['值'].ewm(span=3).mean()

print(df)

时间偏移

python
dates = pd.date_range('2024-01-01', periods=3)

# 添加偏移
future = dates + pd.DateOffset(days=5)
print(future)

# 月末偏移
end_of_month = dates + pd.offsets.MonthEnd()
print(end_of_month)

# 工作日偏移
business_day = dates + pd.offsets.BDay()
print(business_day)

时区处理

python
# 创建带时区的时间
dates = pd.date_range('2024-01-01', periods=3, tz='Asia/Shanghai')
print(dates)

# 转换时区
dates_utc = dates.tz_convert('UTC')
print(dates_utc)

# 去除时区
dates_naive = dates.tz_localize(None)
print(dates_naive)

时间序列分析在金融、气象、销售等领域有广泛应用,掌握时间索引操作非常重要。