简体中文 繁體中文 English 日本語 Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

掌握Pandas日期输出技巧轻松处理时间序列数据从基础格式化到高级应用全面解析日期显示与转换方法

3万

主题

318

科技点

3万

积分

大区版主

木柜子打湿

积分
31894

财Doro三倍冰淇淋无人之境【一阶】立华奏小樱(小丑装)⑨的冰沙以外的星空【二阶】

发表于 2025-10-3 11:40:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

在数据分析和处理领域,时间序列数据是一种常见且重要的数据类型。无论是金融市场的股票价格、企业的销售记录,还是气象数据、传感器读数,这些数据往往都与时间紧密相关。Pandas作为Python数据分析的核心库,提供了强大而灵活的日期时间处理功能,能够帮助我们高效地处理、分析和可视化时间序列数据。

本文将全面介绍Pandas中的日期处理技巧,从基础的日期格式化到高级的时间序列操作,帮助读者掌握Pandas日期输出的各种方法,提升时间序列数据处理的效率和准确性。

Pandas日期时间基础

datetime64和Timestamp对象

Pandas中的日期时间处理主要基于NumPy的datetime64数据类型和Pandas自定义的Timestamp对象。Timestamp是Python标准库datetime的增强版本,提供了更多功能和方法。
  1. import pandas as pd
  2. import numpy as np
  3. # 创建Timestamp对象
  4. ts = pd.Timestamp('2023-05-15')
  5. print(ts)  # 输出: 2023-05-15 00:00:00
  6. print(type(ts))  # 输出: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
  7. # 获取当前时间戳
  8. now = pd.Timestamp.now()
  9. print(now)  # 输出当前时间,例如: 2023-11-05 14:30:45.123456
复制代码

创建日期时间对象的方法

Pandas提供了多种创建日期时间对象的方法:
  1. # 使用字符串创建
  2. date_str = pd.Timestamp('2023-05-15 14:30:00')
  3. print(date_str)
  4. # 使用单独的年、月、日等参数创建
  5. date_params = pd.Timestamp(year=2023, month=5, day=15, hour=14, minute=30)
  6. print(date_params)
  7. # 使用Unix时间戳创建
  8. unix_ts = pd.Timestamp(1684156200, unit='s')  # 单位是秒
  9. print(unix_ts)
  10. # 从numpy datetime64转换
  11. np_dt = np.datetime64('2023-05-15T14:30:00')
  12. pd_dt = pd.Timestamp(np_dt)
  13. print(pd_dt)
复制代码

日期时间索引(DatetimeIndex)

在处理时间序列数据时,DatetimeIndex是一个核心概念,它允许我们将日期时间作为索引,从而进行高效的时间序列操作。
  1. # 创建DatetimeIndex
  2. dates = ['2023-05-01', '2023-05-02', '2023-05-03', '2023-05-04', '2023-05-05']
  3. dt_index = pd.DatetimeIndex(dates)
  4. print(dt_index)
  5. # 创建带有DatetimeIndex的Series
  6. ts_series = pd.Series([10, 20, 30, 40, 50], index=dt_index)
  7. print(ts_series)
  8. # 使用date_range创建日期范围
  9. date_range = pd.date_range(start='2023-05-01', end='2023-05-10')
  10. print(date_range)
  11. # 创建带有频率的日期范围
  12. freq_range = pd.date_range(start='2023-05-01', periods=10, freq='D')  # 每日
  13. print(freq_range)
  14. # 不同频率的日期范围
  15. business_days = pd.date_range(start='2023-05-01', periods=10, freq='B')  # 工作日
  16. monthly = pd.date_range(start='2023-01-01', periods=12, freq='M')  # 月末
  17. quarterly = pd.date_range(start='2023-01-01', periods=4, freq='Q')  # 季末
  18. print("工作日:", business_days[:5])
  19. print("月末:", monthly[:4])
  20. print("季末:", quarterly)
复制代码

基础日期格式化

strftime方法

strftime方法是将日期时间对象格式化为字符串的标准方法,它使用格式代码来控制输出。
  1. # 创建一个Timestamp对象
  2. ts = pd.Timestamp('2023-05-15 14:30:45')
  3. # 基本格式化
  4. print(ts.strftime('%Y-%m-%d'))  # 输出: 2023-05-15
  5. print(ts.strftime('%d/%m/%Y'))  # 输出: 15/05/2023
  6. print(ts.strftime('%H:%M:%S'))  # 输出: 14:30:45
  7. # 组合格式化
  8. print(ts.strftime('%Y-%m-%d %H:%M:%S'))  # 输出: 2023-05-15 14:30:45
  9. print(ts.strftime('%A, %B %d, %Y'))  # 输出: Monday, May 15, 2023
  10. print(ts.strftime('%I:%M %p'))  # 输出: 02:30 PM
复制代码

常用格式化代码

以下是一些常用的日期时间格式化代码:
  1. ts = pd.Timestamp('2023-05-15 14:30:45')
  2. # 年份
  3. print(f"完整年份 (4位): {ts.strftime('%Y')}")  # 输出: 2023
  4. print(f"简写年份 (2位): {ts.strftime('%y')}")  # 输出: 23
  5. # 月份
  6. print(f"月份 (数字): {ts.strftime('%m')}")  # 输出: 05
  7. print(f"月份 (全名): {ts.strftime('%B')}")  # 输出: May
  8. print(f"月份 (缩写): {ts.strftime('%b')}")  # 输出: May
  9. # 日期
  10. print(f"日期 (2位): {ts.strftime('%d')}")  # 输出: 15
  11. print(f"日期 (带序号): {ts.strftime('%d').lstrip('0') + ts.strftime(('st' if ts.strftime('%d')[-1]=='1' else 'nd' if ts.strftime('%d')[-1]=='2' else 'rd' if ts.strftime('%d')[-1]=='3' else 'th'))}")  # 输出: 15th
  12. # 星期
  13. print(f"星期 (全名): {ts.strftime('%A')}")  # 输出: Monday
  14. print(f"星期 (缩写): {ts.strftime('%a')}")  # 输出: Mon
  15. print(f"星期 (数字): {ts.strftime('%w')}")  # 输出: 1 (0=周日, 1=周一, ..., 6=周六)
  16. # 时间
  17. print(f"小时 (24小时制): {ts.strftime('%H')}")  # 输出: 14
  18. print(f"小时 (12小时制): {ts.strftime('%I')}")  # 输出: 02
  19. print(f"分钟: {ts.strftime('%M')}")  # 输出: 30
  20. print(f"秒: {ts.strftime('%S')}")  # 输出: 45
  21. print(f"上午/下午: {ts.strftime('%p')}")  # 输出: PM
  22. # 其他
  23. print(f"一年中的第几天: {ts.strftime('%j')}")  # 输出: 135
  24. print(f"一年中的第几周: {ts.strftime('%U')}")  # 输出: 20 (以周日为一周的开始)
  25. print(f"一年中的第几周: {ts.strftime('%W')}")  # 输出: 20 (以周一为一周的开始)
复制代码

自定义日期显示格式

在实际应用中,我们经常需要根据特定需求自定义日期显示格式:
  1. # 创建一个Timestamp对象
  2. ts = pd.Timestamp('2023-05-15 14:30:45')
  3. # 自定义格式1: "15-May-2023"
  4. custom_format1 = ts.strftime('%d-%b-%Y')
  5. print(custom_format1)
  6. # 自定义格式2: "May 15, 2023 02:30 PM"
  7. custom_format2 = ts.strftime('%B %d, %Y %I:%M %p')
  8. print(custom_format2)
  9. # 自定义格式3: "20230515_143045" (适合文件名)
  10. custom_format3 = ts.strftime('%Y%m%d_%H%M%S')
  11. print(custom_format3)
  12. # 自定义格式4: "Monday, the 15th of May, 2023"
  13. day_with_suffix = ts.strftime('%d').lstrip('0')
  14. if day_with_suffix[-1] == '1' and day_with_suffix != '11':
  15.     day_with_suffix += 'st'
  16. elif day_with_suffix[-1] == '2' and day_with_suffix != '12':
  17.     day_with_suffix += 'nd'
  18. elif day_with_suffix[-1] == '3' and day_with_suffix != '13':
  19.     day_with_suffix += 'rd'
  20. else:
  21.     day_with_suffix += 'th'
  22.    
  23. custom_format4 = ts.strftime(f'%A, the {day_with_suffix} of %B, %Y')
  24. print(custom_format4)
复制代码

日期解析与转换

to_datetime方法

to_datetime是Pandas中用于将各种格式的输入转换为日期时间对象的核心函数:
  1. # 将字符串转换为日期时间
  2. date_str = '2023-05-15'
  3. dt = pd.to_datetime(date_str)
  4. print(dt)
  5. print(type(dt))
  6. # 将多个字符串转换为DatetimeIndex
  7. dates = ['2023-05-01', '2023-05-02', '2023-05-03']
  8. dt_index = pd.to_datetime(dates)
  9. print(dt_index)
  10. # 将Series转换为日期时间
  11. date_series = pd.Series(['2023-05-01', '2023-05-02', '2023-05-03'])
  12. dt_series = pd.to_datetime(date_series)
  13. print(dt_series)
  14. # 将DataFrame的列转换为日期时间
  15. df = pd.DataFrame({'year': [2023, 2023, 2023],
  16.                    'month': [5, 5, 5],
  17.                    'day': [1, 2, 3]})
  18. dt_df = pd.to_datetime(df)
  19. print(dt_df)
复制代码

处理不同格式的日期字符串

实际数据中的日期格式多种多样,to_datetime提供了灵活的参数来处理不同格式:
  1. # 标准格式
  2. print(pd.to_datetime('2023-05-15'))  # ISO格式
  3. print(pd.to_datetime('05/15/2023'))  # 美国格式
  4. print(pd.to_datetime('15/05/2023'))  # 欧洲格式
  5. # 指定格式
  6. print(pd.to_datetime('15-05-2023', format='%d-%m-%Y'))
  7. print(pd.to_datetime('May 15, 2023', format='%B %d, %Y'))
  8. # 处理混合格式
  9. mixed_dates = ['2023-05-01', '05/02/2023', '03 May 2023']
  10. print(pd.to_datetime(mixed_dates))
  11. # 处理Unix时间戳
  12. print(pd.to_datetime(1684156200, unit='s'))  # 秒
  13. print(pd.to_datetime(1684156200000, unit='ms'))  # 毫秒
  14. # 处理Excel日期序列号
  15. excel_date = 45047  # 2023-05-15
  16. print(pd.to_datetime(excel_date, unit='D', origin='1899-12-30'))
复制代码

处理缺失值和异常值

在真实数据中,日期字段可能包含缺失值或异常值,to_datetime提供了处理这些情况的参数:
  1. # 处理缺失值
  2. dates_with_na = ['2023-05-01', '2023-05-02', None, '2023-05-04']
  3. print(pd.to_datetime(dates_with_na))
  4. # 使用errors参数处理异常值
  5. invalid_dates = ['2023-05-01', 'invalid_date', '2023-05-03']
  6. # errors='coerce' 将无效值转为NaT (Not a Time)
  7. print(pd.to_datetime(invalid_dates, errors='coerce'))
  8. # errors='ignore' 将保留原始输入
  9. print(pd.to_datetime(invalid_dates, errors='ignore'))
  10. # 使用dayfirst和yearfirst处理模糊日期
  11. ambiguous_date = '01/05/2023'  # 可能是1月5日或5月1日
  12. print(pd.to_datetime(ambiguous_date))  # 默认: monthfirst
  13. print(pd.to_datetime(ambiguous_date, dayfirst=True))  # 日在前
  14. print(pd.to_datetime(ambiguous_date, yearfirst=True))  # 年在前
复制代码

时间序列数据操作

时间戳提取

从日期时间对象中提取特定部分是常见的需求:
  1. # 创建一个DatetimeIndex
  2. dates = pd.date_range('2023-05-01', periods=5, freq='D')
  3. ts = pd.Series(range(5), index=dates)
  4. # 提取日期时间组件
  5. print("日期:", ts.index.day)
  6. print("月份:", ts.index.month)
  7. print("年份:", ts.index.year)
  8. print("小时:", ts.index.hour)
  9. print("分钟:", ts.index.minute)
  10. print("秒:", ts.index.second)
  11. print("星期几:", ts.index.dayofweek)  # 0=周一, 1=周二, ..., 6=周日
  12. print("一年中的第几天:", ts.index.dayofyear)
  13. print("一年中的第几周:", ts.index.week)
  14. print("季度:", ts.index.quarter)
  15. print("是否为月初:", ts.index.is_month_start)
  16. print("是否为月末:", ts.index.is_month_end)
  17. print("是否为季初:", ts.index.is_quarter_start)
  18. print("是否为季末:", ts.index.is_quarter_end)
  19. print("是否为年初:", ts.index.is_year_start)
  20. print("是否为年末:", ts.index.is_year_end)
复制代码

时间范围生成

Pandas提供了多种生成时间范围的方法:
  1. # 基本日期范围
  2. print(pd.date_range(start='2023-01-01', end='2023-01-10'))
  3. # 指定周期数
  4. print(pd.date_range(start='2023-01-01', periods=10))
  5. # 指定频率
  6. print(pd.date_range(start='2023-01-01', periods=10, freq='D'))  # 日
  7. print(pd.date_range(start='2023-01-01', periods=10, freq='W'))  # 周
  8. print(pd.date_range(start='2023-01-01', periods=10, freq='M'))  # 月
  9. print(pd.date_range(start='2023-01-01', periods=10, freq='Q'))  # 季
  10. print(pd.date_range(start='2023-01-01', periods=10, freq='Y'))  # 年
  11. # 工作日
  12. print(pd.date_range(start='2023-01-01', periods=10, freq='B'))
  13. # 自定义频率
  14. print(pd.date_range(start='2023-01-01', periods=10, freq='2D'))  # 每2天
  15. print(pd.date_range(start='2023-01-01', periods=10, freq='3H'))  # 每3小时
  16. print(pd.date_range(start='2023-01-01', periods=10, freq='30T'))  # 每30分钟
  17. # 使用date_range创建时间序列
  18. ts = pd.Series(np.random.randn(10),
  19.                index=pd.date_range('2023-01-01', periods=10, freq='D'))
  20. print(ts)
复制代码

时间重采样

重采样是将时间序列从一个频率转换到另一个频率的过程:
  1. # 创建一个高频时间序列
  2. high_freq_ts = pd.Series(np.random.randn(100),
  3.                          index=pd.date_range('2023-01-01', periods=100, freq='D'))
  4. # 降采样 (从高频到低频)
  5. # 按月采样,计算每月均值
  6. monthly_mean = high_freq_ts.resample('M').mean()
  7. print(monthly_mean)
  8. # 按周采样,计算每周总和
  9. weekly_sum = high_freq_ts.resample('W').sum()
  10. print(weekly_sum)
  11. # 按季度采样,计算每季度的最大值
  12. quarterly_max = high_freq_ts.resample('Q').max()
  13. print(quarterly_max)
  14. # 升采样 (从低频到高频)
  15. # 创建一个低频时间序列
  16. low_freq_ts = pd.Series([10, 20, 30, 40],
  17.                         index=pd.date_range('2023-01-01', periods=4, freq='M'))
  18. # 升采样到日频率,使用前向填充
  19. daily_ffill = low_freq_ts.resample('D').ffill()
  20. print(daily_ffill.head(10))
  21. # 升采样到日频率,使用后向填充
  22. daily_bfill = low_freq_ts.resample('D').bfill()
  23. print(daily_bfill.head(10))
  24. # 升采样到日频率,使用线性插值
  25. daily_interpolate = low_freq_ts.resample('D').interpolate()
  26. print(daily_interpolate.head(10))
  27. # 自定义聚合函数
  28. # 计算每月的标准差
  29. monthly_std = high_freq_ts.resample('M').std()
  30. print(monthly_std)
  31. # 计算每周的第一个值和最后一个值
  32. weekly_first_last = high_freq_ts.resample('W').agg(['first', 'last'])
  33. print(weekly_first_last)
复制代码

高级日期应用

时区处理

处理不同时区的时间数据是全球化应用中的常见需求:
  1. # 创建一个无时区的时间序列
  2. ts_no_tz = pd.Series(range(5),
  3.                      index=pd.date_range('2023-01-01', periods=5, freq='D'))
  4. print("无时区:", ts_no_tz.index)
  5. # 本地化时区
  6. ts_tz = ts_no_tz.tz_localize('UTC')
  7. print("UTC时区:", ts_tz.index)
  8. # 转换时区
  9. ts_est = ts_tz.tz_convert('US/Eastern')
  10. print("美国东部时区:", ts_est.index)
  11. # 转换为其他时区
  12. ts_cst = ts_tz.tz_convert('US/Central')
  13. print("美国中部时区:", ts_cst.index)
  14. # 获取所有可用时区
  15. import pytz
  16. print("可用时区数量:", len(pytz.all_timezones))
  17. print("部分时区示例:", list(pytz.all_timezones)[:10])
  18. # 处理夏令时
  19. # 创建一个跨越夏令时变化的时间范围
  20. dst_range = pd.date_range('2023-03-10', '2023-03-13', freq='6H', tz='US/Eastern')
  21. print("跨越夏令时变化的时间范围:", dst_range)
  22. # 处理时区模糊时间
  23. # 有些时区在夏令时切换时会有重复或缺失的时间
  24. try:
  25.     # 尝试创建一个模糊时间
  26.     ambiguous_time = pd.Timestamp('2023-11-05 01:30:00', tz='US/Eastern')
  27. except Exception as e:
  28.     print("模糊时间错误:", e)
  29. # 解决模糊时间问题
  30. ambiguous_time = pd.Timestamp('2023-11-05 01:30:00', tz='US/Eastern', ambiguous=True)
  31. print("解决后的模糊时间:", ambiguous_time)
复制代码

时间差计算

计算时间之间的差异是时间序列分析的重要部分:
  1. # 创建两个时间戳
  2. start = pd.Timestamp('2023-01-01')
  3. end = pd.Timestamp('2023-12-31')
  4. # 计算时间差
  5. time_diff = end - start
  6. print("时间差:", time_diff)
  7. print("时间差类型:", type(time_diff))
  8. # 访问时间差的各个组件
  9. print("天数:", time_diff.days)
  10. print("秒数:", time_diff.seconds)
  11. print("总秒数:", time_diff.total_seconds())
  12. # 计算时间序列中的时间差
  13. dates = pd.date_range('2023-01-01', periods=5, freq='D')
  14. ts = pd.Series(range(5), index=dates)
  15. # 计算相邻时间点之间的差异
  16. diffs = ts.index.to_series().diff()
  17. print("相邻时间差:", diffs)
  18. # 计算相对于第一个时间点的时间差
  19. from_start = ts.index - ts.index[0]
  20. print("相对于起始时间的时间差:", from_start)
  21. # 使用Timedelta进行时间运算
  22. one_day = pd.Timedelta(days=1)
  23. one_week = pd.Timedelta(weeks=1)
  24. one_hour = pd.Timedelta(hours=1)
  25. print("一天后:", start + one_day)
  26. print("一周前:", end - one_week)
  27. print("一小时后:", start + one_hour)
  28. # 时间差的算术运算
  29. delta1 = pd.Timedelta(days=10)
  30. delta2 = pd.Timedelta(days=5)
  31. print("时间差相加:", delta1 + delta2)
  32. print("时间差相减:", delta1 - delta2)
  33. print("时间差乘以2:", delta1 * 2)
  34. print("时间差除以2:", delta1 / 2)
  35. # 计算年龄
  36. birth_date = pd.Timestamp('1990-05-15')
  37. today = pd.Timestamp.now()
  38. age = today - birth_date
  39. print("从出生到现在的时间差:", age)
  40. print("年龄(年):", age.days / 365.25)
复制代码

移动窗口操作

移动窗口操作是时间序列分析中常用的技术,用于平滑数据或计算滚动统计量:
  1. # 创建一个时间序列
  2. np.random.seed(42)
  3. ts = pd.Series(np.random.randn(100),
  4.                index=pd.date_range('2023-01-01', periods=100, freq='D'))
  5. # 计算滚动均值
  6. rolling_mean = ts.rolling(window=7).mean()  # 7天滚动均值
  7. print("滚动均值:", rolling_mean.head(10))
  8. # 计算滚动标准差
  9. rolling_std = ts.rolling(window=7).std()
  10. print("滚动标准差:", rolling_std.head(10))
  11. # 计算滚动最大值和最小值
  12. rolling_max = ts.rolling(window=7).max()
  13. rolling_min = ts.rolling(window=7).min()
  14. print("滚动最大值:", rolling_max.head(10))
  15. print("滚动最小值:", rolling_min.head(10))
  16. # 计算滚动相关系数
  17. ts2 = pd.Series(np.random.randn(100),
  18.                 index=pd.date_range('2023-01-01', periods=100, freq='D'))
  19. rolling_corr = ts.rolling(window=7).corr(ts2)
  20. print("滚动相关系数:", rolling_corr.head(10))
  21. # 指数加权移动平均
  22. ewm_mean = ts.ewm(span=7).mean()
  23. print("指数加权移动平均:", ewm_mean.head(10))
  24. # 扩展窗口计算
  25. expanding_mean = ts.expanding().mean()
  26. print("扩展窗口均值:", expanding_mean.head(10))
  27. # 自定义滚动窗口函数
  28. # 例如,计算滚动范围内的中位数与均值的比值
  29. def median_mean_ratio(x):
  30.     return np.median(x) / np.mean(x) if np.mean(x) != 0 else 0
  31. custom_rolling = ts.rolling(window=7).apply(median_mean_ratio)
  32. print("自定义滚动函数:", custom_rolling.head(10))
  33. # 可变时间窗口
  34. # 例如,计算每7个日历日的滚动均值,而不是7个观测值
  35. time_rolling = ts.rolling(window='7D').mean()
  36. print("时间窗口滚动均值:", time_rolling.head(10))
复制代码

自定义日历和节假日处理

在金融和商业分析中,考虑交易日和节假日非常重要:
  1. # 创建自定义工作日日历
  2. from pandas.tseries.offsets import CustomBusinessDay
  3. from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday
  4. # 定义美国联邦假日
  5. class USFederalHolidayCalendar(AbstractHolidayCalendar):
  6.     rules = [
  7.         Holiday('New Years Day', month=1, day=1, observance=nearest_workday),
  8.         Holiday('Martin Luther King Jr. Day', month=1, day=1, offset=pd.DateOffset(weekday=0, weeks=3)),
  9.         Holiday('Presidents Day', month=2, day=1, offset=pd.DateOffset(weekday=0, weeks=3)),
  10.         Holiday('Memorial Day', month=5, day=31, offset=pd.DateOffset(weekday=0, weeks=-1)),
  11.         Holiday('Independence Day', month=7, day=4, observance=nearest_workday),
  12.         Holiday('Labor Day', month=9, day=1, offset=pd.DateOffset(weekday=0, weeks=1)),
  13.         Holiday('Columbus Day', month=10, day=1, offset=pd.DateOffset(weekday=0, weeks=2)),
  14.         Holiday('Veterans Day', month=11, day=11, observance=nearest_workday),
  15.         Holiday('Thanksgiving', month=11, day=1, offset=pd.DateOffset(weekday=3, weeks=4)),
  16.         Holiday('Christmas', month=12, day=25, observance=nearest_workday)
  17.     ]
  18. # 创建自定义工作日
  19. us_bday = CustomBusinessDay(calendar=USFederalHolidayCalendar())
  20. # 生成2023年的工作日
  21. us_business_days = pd.date_range(start='2023-01-01', end='2023-12-31', freq=us_bday)
  22. print("2023年美国工作日数量:", len(us_business_days))
  23. print("部分工作日示例:", us_business_days[:10])
  24. # 检查特定日期是否为工作日
  25. test_date = pd.Timestamp('2023-07-04')  # 美国独立日
  26. is_business_day = test_date in us_business_days
  27. print(f"{test_date} 是工作日吗? {is_business_day}")
  28. # 计算两个日期之间的工作日数
  29. start_date = pd.Timestamp('2023-01-01')
  30. end_date = pd.Timestamp('2023-12-31')
  31. business_days_between = len(pd.date_range(start_date, end_date, freq=us_bday))
  32. print(f"{start_date} 和 {end_date} 之间的工作日数: {business_days_between}")
  33. # 添加自定义假日
  34. class CustomBusinessCalendar(AbstractHolidayCalendar):
  35.     rules = [
  36.         Holiday('Company Founding Day', month=6, day=15)
  37.     ]
  38. custom_bday = CustomBusinessDay(calendar=CustomBusinessCalendar())
  39. custom_business_days = pd.date_range(start='2023-01-01', end='2023-12-31', freq=custom_bday)
  40. print("考虑公司假日的2023年工作日数量:", len(custom_business_days))
  41. # 使用自定义工作日进行时间序列操作
  42. # 创建一个只在工作日有数据的时间序列
  43. business_ts = pd.Series(np.random.randn(len(us_business_days)),
  44.                         index=us_business_days)
  45. print("工作日时间序列:", business_ts.head(10))
  46. # 计算工作日滚动均值
  47. business_rolling_mean = business_ts.rolling(window=5).mean()
  48. print("工作日滚动均值:", business_rolling_mean.head(10))
复制代码

性能优化技巧

大规模时间序列数据处理

处理大规模时间序列数据时,性能优化至关重要:
  1. # 创建一个大型时间序列
  2. large_ts = pd.Series(np.random.randn(1000000),
  3.                      index=pd.date_range('2000-01-01', periods=1000000, freq='H'))
  4. # 使用适当的数据类型
  5. # 将时间索引转换为更高效的datetime64[ns]类型
  6. large_ts.index = large_ts.index.astype('datetime64[ns]')
  7. print("时间索引数据类型:", large_ts.index.dtype)
  8. # 使用向量化操作而不是循环
  9. # 不好的方式:使用循环
  10. def bad_way(ts):
  11.     result = pd.Series(index=ts.index, dtype=float)
  12.     for i in range(1, len(ts)):
  13.         result.iloc[i] = ts.iloc[i] - ts.iloc[i-1]
  14.     return result
  15. # 好的方式:使用向量化操作
  16. def good_way(ts):
  17.     return ts.diff()
  18. # 比较性能
  19. import time
  20. start_time = time.time()
  21. bad_result = bad_way(large_ts.head(1000))  # 只使用前1000个点,否则太慢
  22. bad_time = time.time() - start_time
  23. start_time = time.time()
  24. good_result = good_way(large_ts)
  25. good_time = time.time() - start_time
  26. print(f"循环方式耗时 (1000点): {bad_time:.4f}秒")
  27. print(f"向量化方式耗时 (1000000点): {good_time:.4f}秒")
  28. # 使用分类数据类型处理重复的字符串数据
  29. # 假设我们有一个带有重复类别标签的时间序列
  30. categories = ['A', 'B', 'C', 'D', 'E']
  31. large_ts_with_categories = pd.DataFrame({
  32.     'value': np.random.randn(1000000),
  33.     'category': np.random.choice(categories, 1000000)
  34. }, index=pd.date_range('2000-01-01', periods=1000000, freq='H'))
  35. # 将类别列转换为分类类型
  36. large_ts_with_categories['category'] = large_ts_with_categories['category'].astype('category')
  37. print("类别列数据类型:", large_ts_with_categories['category'].dtype)
  38. # 使用适当的数据结构
  39. # 对于固定频率的时间序列,使用PeriodIndex可能更高效
  40. period_index = pd.period_range('2000-01-01', periods=1000000, freq='H')
  41. period_ts = pd.Series(np.random.randn(1000000), index=period_index)
  42. print("周期索引示例:", period_ts.head())
  43. # 分块处理大型数据集
  44. def process_chunk(chunk):
  45.     # 对每个数据块进行处理
  46.     return chunk.resample('D').mean()
  47. # 将大型时间序列分成多个块
  48. chunk_size = 100000
  49. chunks = [large_ts[i:i+chunk_size] for i in range(0, len(large_ts), chunk_size)]
  50. # 处理每个块
  51. processed_chunks = [process_chunk(chunk) for chunk in chunks]
  52. # 合并结果
  53. final_result = pd.concat(processed_chunks)
  54. print("分块处理结果:", final_result.head())
复制代码

向量化操作

向量化操作是提高Pandas性能的关键:
  1. # 创建一个时间序列
  2. ts = pd.Series(np.random.randn(10000),
  3.                index=pd.date_range('2000-01-01', periods=10000, freq='D'))
  4. # 向量化操作示例1:计算移动平均
  5. # 不好的方式:使用循环
  6. def rolling_mean_loop(ts, window):
  7.     result = pd.Series(index=ts.index, dtype=float)
  8.     for i in range(window-1, len(ts)):
  9.         result.iloc[i] = ts.iloc[i-window+1:i+1].mean()
  10.     return result
  11. # 好的方式:使用向量化操作
  12. def rolling_mean_vectorized(ts, window):
  13.     return ts.rolling(window=window).mean()
  14. # 比较性能
  15. start_time = time.time()
  16. loop_result = rolling_mean_loop(ts.head(1000), 7)  # 只使用前1000个点
  17. loop_time = time.time() - start_time
  18. start_time = time.time()
  19. vectorized_result = rolling_mean_vectorized(ts, 7)
  20. vectorized_time = time.time() - start_time
  21. print(f"循环方式耗时 (1000点): {loop_time:.4f}秒")
  22. print(f"向量化方式耗时 (10000点): {vectorized_time:.4f}秒")
  23. # 向量化操作示例2:计算季节性模式
  24. # 不好的方式:使用循环
  25. def seasonal_pattern_loop(ts):
  26.     result = pd.Series(index=ts.index, dtype=float)
  27.     for i in range(len(ts)):
  28.         month = ts.index[i].month
  29.         result.iloc[i] = ts[ts.index.month == month].mean()
  30.     return result
  31. # 好的方式:使用向量化操作
  32. def seasonal_pattern_vectorized(ts):
  33.     monthly_means = ts.groupby(ts.index.month).transform('mean')
  34.     return monthly_means
  35. # 比较性能
  36. start_time = time.time()
  37. loop_seasonal = seasonal_pattern_loop(ts.head(1000))  # 只使用前1000个点
  38. loop_seasonal_time = time.time() - start_time
  39. start_time = time.time()
  40. vectorized_seasonal = seasonal_pattern_vectorized(ts)
  41. vectorized_seasonal_time = time.time() - start_time
  42. print(f"循环方式耗时 (1000点): {loop_seasonal_time:.4f}秒")
  43. print(f"向量化方式耗时 (10000点): {vectorized_seasonal_time:.4f}秒")
  44. # 向量化操作示例3:计算日期差异
  45. # 不好的方式:使用循环
  46. def date_diff_loop(dates):
  47.     result = pd.Series(index=dates.index, dtype='timedelta64[ns]')
  48.     for i in range(1, len(dates)):
  49.         result.iloc[i] = dates.iloc[i] - dates.iloc[i-1]
  50.     return result
  51. # 好的方式:使用向量化操作
  52. def date_diff_vectorized(dates):
  53.     return dates.diff()
  54. # 比较性能
  55. start_time = time.time()
  56. loop_diff = date_diff_loop(ts.head(1000).index.to_series())  # 只使用前1000个点
  57. loop_diff_time = time.time() - start_time
  58. start_time = time.time()
  59. vectorized_diff = date_diff_vectorized(ts.index.to_series())
  60. vectorized_diff_time = time.time() - start_time
  61. print(f"循环方式耗时 (1000点): {loop_diff_time:.4f}秒")
  62. print(f"向量化方式耗时 (10000点): {vectorized_diff_time:.4f}秒")
复制代码

实际案例研究

金融数据分析

金融数据分析是时间序列处理的典型应用场景:
  1. # 模拟股票价格数据
  2. np.random.seed(42)
  3. dates = pd.date_range('2020-01-01', '2022-12-31', freq='B')  # 工作日
  4. price_changes = np.random.normal(0.001, 0.02, len(dates))  # 每日价格变化
  5. initial_price = 100.0
  6. prices = [initial_price]
  7. for change in price_changes:
  8.     prices.append(prices[-1] * (1 + change))
  9. stock_prices = pd.Series(prices[1:], index=dates)
  10. print("股票价格数据:", stock_prices.head())
  11. # 计算日收益率
  12. daily_returns = stock_prices.pct_change()
  13. print("日收益率:", daily_returns.head())
  14. # 计算移动平均
  15. ma_20 = stock_prices.rolling(window=20).mean()  # 20日移动平均
  16. ma_50 = stock_prices.rolling(window=50).mean()  # 50日移动平均
  17. # 计算布林带
  18. rolling_std = stock_prices.rolling(window=20).std()
  19. upper_band = ma_20 + (rolling_std * 2)
  20. lower_band = ma_20 - (rolling_std * 2)
  21. # 计算相对强弱指数 (RSI)
  22. def calculate_rsi(prices, window=14):
  23.     delta = prices.diff()
  24.     gain = delta.where(delta > 0, 0)
  25.     loss = -delta.where(delta < 0, 0)
  26.    
  27.     avg_gain = gain.rolling(window=window).mean()
  28.     avg_loss = loss.rolling(window=window).mean()
  29.    
  30.     rs = avg_gain / avg_loss
  31.     rsi = 100 - (100 / (1 + rs))
  32.    
  33.     return rsi
  34. rsi = calculate_rsi(stock_prices)
  35. # 计算年化波动率
  36. volatility = daily_returns.std() * np.sqrt(252)  # 252个交易日
  37. print(f"年化波动率: {volatility:.2%}")
  38. # 计算最大回撤
  39. cummax = stock_prices.cummax()
  40. drawdown = (stock_prices - cummax) / cummax
  41. max_drawdown = drawdown.min()
  42. print(f"最大回撤: {max_drawdown:.2%}")
  43. # 可视化结果
  44. import matplotlib.pyplot as plt
  45. plt.figure(figsize=(12, 8))
  46. # 价格和移动平均
  47. plt.subplot(2, 1, 1)
  48. plt.plot(stock_prices, label='Price')
  49. plt.plot(ma_20, label='MA 20')
  50. plt.plot(ma_50, label='MA 50')
  51. plt.fill_between(stock_prices.index, upper_band, lower_band, color='gray', alpha=0.3, label='Bollinger Bands')
  52. plt.title('Stock Price with Moving Averages and Bollinger Bands')
  53. plt.legend()
  54. # RSI
  55. plt.subplot(2, 1, 2)
  56. plt.plot(rsi, label='RSI')
  57. plt.axhline(70, color='red', linestyle='--', alpha=0.5)
  58. plt.axhline(30, color='green', linestyle='--', alpha=0.5)
  59. plt.title('Relative Strength Index (RSI)')
  60. plt.legend()
  61. plt.tight_layout()
  62. plt.show()
复制代码

销售数据分析

销售数据分析通常涉及季节性模式和趋势分析:
  1. # 模拟销售数据
  2. np.random.seed(42)
  3. dates = pd.date_range('2018-01-01', '2022-12-31', freq='D')
  4. # 创建基础趋势
  5. trend = np.linspace(100, 300, len(dates))
  6. # 添加季节性模式(年度和每周)
  7. seasonal_yearly = 50 * np.sin(2 * np.pi * np.arange(len(dates)) / 365.25)
  8. seasonal_weekly = 20 * np.sin(2 * np.pi * np.arange(len(dates)) / 7)
  9. # 添加随机噪声
  10. noise = np.random.normal(0, 15, len(dates))
  11. # 组合所有组件
  12. sales = trend + seasonal_yearly + seasonal_weekly + noise
  13. sales = np.maximum(sales, 10)  # 确保销售值为正
  14. # 创建周末和节假日效应
  15. weekends = (dates.dayofweek >= 5)  # 周六和周日
  16. holidays = pd.to_datetime(['2018-01-01', '2018-07-04', '2018-12-25',
  17.                           '2019-01-01', '2019-07-04', '2019-12-25',
  18.                           '2020-01-01', '2020-07-04', '2020-12-25',
  19.                           '2021-01-01', '2021-07-04', '2021-12-25',
  20.                           '2022-01-01', '2022-07-04', '2022-12-25'])
  21. # 周末销售增加50%
  22. sales[weekends] *= 1.5
  23. # 节假日销售增加100%
  24. for holiday in holidays:
  25.     if holiday in dates:
  26.         idx = np.where(dates == holiday)[0][0]
  27.         sales[idx] *= 2.0
  28. # 创建销售时间序列
  29. sales_ts = pd.Series(sales, index=dates)
  30. print("销售数据:", sales_ts.head())
  31. # 按月聚合销售数据
  32. monthly_sales = sales_ts.resample('M').sum()
  33. print("月度销售数据:", monthly_sales.head())
  34. # 按年聚合销售数据
  35. yearly_sales = sales_ts.resample('Y').sum()
  36. print("年度销售数据:", yearly_sales)
  37. # 计算同比和环比增长
  38. monthly_yoy_growth = monthly_sales.pct_change(12) * 100  # 同比增长
  39. monthly_mom_growth = monthly_sales.pct_change(1) * 100   # 环比增长
  40. print("月度同比增长率(%):", monthly_yoy_growth.dropna().head())
  41. print("月度环比增长率(%):", monthly_mom_growth.dropna().head())
  42. # 分解时间序列(趋势、季节性和残差)
  43. from statsmodels.tsa.seasonal import seasonal_decompose
  44. # 使用月度数据进行分解
  45. monthly_decomposition = seasonal_decompose(monthly_sales, model='additive', period=12)
  46. trend = monthly_decomposition.trend
  47. seasonal = monthly_decomposition.seasonal
  48. residual = monthly_decomposition.resid
  49. # 可视化分解结果
  50. plt.figure(figsize=(12, 10))
  51. plt.subplot(4, 1, 1)
  52. plt.plot(monthly_sales, label='Original')
  53. plt.title('Monthly Sales')
  54. plt.legend()
  55. plt.subplot(4, 1, 2)
  56. plt.plot(trend, label='Trend')
  57. plt.title('Trend Component')
  58. plt.legend()
  59. plt.subplot(4, 1, 3)
  60. plt.plot(seasonal, label='Seasonal')
  61. plt.title('Seasonal Component')
  62. plt.legend()
  63. plt.subplot(4, 1, 4)
  64. plt.plot(residual, label='Residual')
  65. plt.title('Residual Component')
  66. plt.legend()
  67. plt.tight_layout()
  68. plt.show()
  69. # 计算销售预测(简单移动平均)
  70. forecast_period = 12  # 预测未来12个月
  71. last_values = monthly_sales.tail(12)  # 使用最近12个月的值
  72. forecast = np.mean(last_values)  # 简单平均预测
  73. print(f"未来12个月的销售预测: {forecast:.2f}")
  74. # 更高级的预测方法(指数平滑)
  75. from statsmodels.tsa.holtwinters import ExponentialSmoothing
  76. # 拟合模型
  77. model = ExponentialSmoothing(monthly_sales, trend='add', seasonal='add', seasonal_periods=12).fit()
  78. # 进行预测
  79. forecast = model.forecast(forecast_period)
  80. print("指数平滑预测结果:", forecast)
  81. # 可视化预测结果
  82. plt.figure(figsize=(12, 6))
  83. plt.plot(monthly_sales, label='Historical Sales')
  84. plt.plot(forecast, label='Forecast', color='red')
  85. plt.title('Sales Forecast')
  86. plt.legend()
  87. plt.show()
复制代码

网站流量分析

网站流量分析通常涉及处理高频时间序列数据:
  1. # 模拟网站流量数据
  2. np.random.seed(42)
  3. dates = pd.date_range('2023-01-01', '2023-12-31', freq='H')
  4. # 创建基础流量模式(日间和夜间)
  5. hourly_pattern = np.array([5, 3, 2, 1, 1, 2, 5, 10, 15, 20, 25, 30,
  6.                           35, 40, 45, 50, 55, 60, 65, 70, 60, 50, 40, 30])
  7. # 创建周模式(工作日vs周末)
  8. weekly_pattern = np.ones(7)
  9. weekly_pattern[5:7] = 0.7  # 周末流量较低
  10. # 创建年模式(考虑季节性)
  11. day_of_year = np.array([d.dayofyear for d in dates])
  12. yearly_pattern = 1 + 0.3 * np.sin(2 * np.pi * day_of_year / 365.25)
  13. # 组合所有模式
  14. base_traffic = np.array([hourly_pattern[d.hour] * weekly_pattern[d.dayofweek] * yearly_pattern[i]
  15.                          for i, d in enumerate(dates)])
  16. # 添加随机波动
  17. random_variation = np.random.normal(1, 0.1, len(dates))
  18. traffic = base_traffic * random_variation
  19. # 添加特殊事件(如促销活动)
  20. special_events = [
  21.     {'date': '2023-01-01', 'factor': 1.5, 'duration': 24},  # 新年
  22.     {'date': '2023-07-04', 'factor': 0.7, 'duration': 24},  # 美国独立日
  23.     {'date': '2023-11-24', 'factor': 0.5, 'duration': 24},  # 感恩节
  24.     {'date': '2023-11-25', 'factor': 2.0, 'duration': 24},  # 黑色星期五
  25.     {'date': '2023-12-25', 'factor': 0.3, 'duration': 48},  # 圣诞节
  26. ]
  27. for event in special_events:
  28.     start = pd.Timestamp(event['date'])
  29.     end = start + pd.Timedelta(hours=event['duration']-1)
  30.     mask = (dates >= start) & (dates <= end)
  31.     traffic[mask] *= event['factor']
  32. # 创建网站流量时间序列
  33. traffic_ts = pd.Series(traffic, index=dates)
  34. print("网站流量数据:", traffic_ts.head())
  35. # 按天聚合流量数据
  36. daily_traffic = traffic_ts.resample('D').sum()
  37. print("日流量数据:", daily_traffic.head())
  38. # 按周聚合流量数据
  39. weekly_traffic = traffic_ts.resample('W').sum()
  40. print("周流量数据:", weekly_traffic.head())
  41. # 按月聚合流量数据
  42. monthly_traffic = traffic_ts.resample('M').sum()
  43. print("月流量数据:", monthly_traffic.head())
  44. # 分析日内流量模式
  45. hourly_avg = traffic_ts.groupby(traffic_ts.index.hour).mean()
  46. print("平均每小时流量:", hourly_avg)
  47. # 分析周内流量模式
  48. daily_avg = traffic_ts.groupby(traffic_ts.index.dayofweek).mean()
  49. days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  50. daily_avg.index = days
  51. print("平均每日流量:", daily_avg)
  52. # 分析月度流量模式
  53. monthly_avg = traffic_ts.groupby(traffic_ts.index.month).mean()
  54. print("平均每月流量:", monthly_avg)
  55. # 检测异常流量
  56. # 使用Z-score方法检测异常
  57. z_scores = (traffic_ts - traffic_ts.mean()) / traffic_ts.std()
  58. threshold = 3  # 3个标准差
  59. anomalies = traffic_ts[abs(z_scores) > threshold]
  60. print("异常流量数据点:", anomalies.head())
  61. # 检测流量突增
  62. # 计算每小时流量的变化率
  63. pct_change = traffic_ts.pct_change()
  64. spikes = traffic_ts[pct_change > 1.0]  # 增长超过100%
  65. print("流量突增:", spikes.head())
  66. # 可视化流量模式
  67. plt.figure(figsize=(15, 10))
  68. # 日内流量模式
  69. plt.subplot(2, 2, 1)
  70. hourly_avg.plot(kind='bar')
  71. plt.title('Average Hourly Traffic Pattern')
  72. plt.xlabel('Hour of Day')
  73. plt.ylabel('Average Traffic')
  74. # 周内流量模式
  75. plt.subplot(2, 2, 2)
  76. daily_avg.plot(kind='bar')
  77. plt.title('Average Daily Traffic Pattern')
  78. plt.xlabel('Day of Week')
  79. plt.ylabel('Average Traffic')
  80. # 月度流量趋势
  81. plt.subplot(2, 2, 3)
  82. monthly_traffic.plot()
  83. plt.title('Monthly Traffic Trend')
  84. plt.xlabel('Month')
  85. plt.ylabel('Total Traffic')
  86. # 异常流量检测
  87. plt.subplot(2, 2, 4)
  88. traffic_ts.plot(figsize=(12, 6))
  89. anomalies.plot(style='ro', markersize=5)
  90. plt.title('Traffic Anomalies')
  91. plt.xlabel('Date')
  92. plt.ylabel('Traffic')
  93. plt.tight_layout()
  94. plt.show()
  95. # 流量预测(使用ARIMA模型)
  96. from statsmodels.tsa.arima.model import ARIMA
  97. # 使用日流量数据进行预测
  98. # 确保没有缺失值
  99. daily_traffic = daily_traffic.asfreq('D')
  100. # 拟合ARIMA模型
  101. model = ARIMA(daily_traffic, order=(1, 1, 1))
  102. model_fit = model.fit()
  103. # 预测未来7天的流量
  104. forecast = model_fit.forecast(steps=7)
  105. print("未来7天流量预测:", forecast)
  106. # 可视化预测结果
  107. plt.figure(figsize=(12, 6))
  108. plt.plot(daily_traffic, label='Historical Traffic')
  109. plt.plot(forecast, label='Forecast', color='red')
  110. plt.title('Traffic Forecast')
  111. plt.xlabel('Date')
  112. plt.ylabel('Traffic')
  113. plt.legend()
  114. plt.show()
复制代码

总结与最佳实践

Pandas提供了强大而灵活的日期时间处理功能,使我们能够高效地处理时间序列数据。本文从基础到高级,全面介绍了Pandas中的日期处理技巧,包括:

1. 基础日期时间对象:理解Timestamp和DatetimeIndex是处理时间序列数据的基础。
2. 日期格式化:使用strftime方法可以灵活地格式化日期时间输出。
3. 日期解析与转换:to_datetime函数能够处理各种格式的日期字符串,并提供了处理缺失值和异常值的选项。
4. 时间序列操作:包括时间戳提取、时间范围生成和时间重采样等技术。
5. 高级日期应用:时区处理、时间差计算、移动窗口操作和自定义日历处理等高级功能。
6. 性能优化:使用适当的数据类型、向量化操作和分块处理等技术可以提高大规模时间序列数据处理的效率。
7. 实际应用案例:金融数据分析、销售数据分析和网站流量分析等实际场景展示了Pandas日期处理功能的实际应用。

最佳实践

在使用Pandas处理日期时间数据时,以下最佳实践可以帮助您提高效率和代码质量:

1. 使用适当的数据类型:确保日期时间列使用正确的数据类型(datetime64[ns]),而不是字符串。
  1. # 不好的方式
  2.    df['date'] = df['date'].astype(str)
  3.    
  4.    # 好的方式
  5.    df['date'] = pd.to_datetime(df['date'])
复制代码

1. 设置日期时间索引:对于时间序列数据,将日期时间列设置为索引可以提高操作效率。
  1. df = df.set_index('date')
复制代码

1. 使用向量化操作:避免使用循环处理时间序列数据,尽量使用Pandas提供的向量化操作。
  1. # 不好的方式
  2.    for i in range(1, len(ts)):
  3.        result[i] = ts[i] - ts[i-1]
  4.    
  5.    # 好的方式
  6.    result = ts.diff()
复制代码

1. 处理时区信息:如果数据涉及时区,确保正确处理时区转换。
  1. # 本地化时区
  2.    ts = ts.tz_localize('UTC')
  3.    
  4.    # 转换时区
  5.    ts = ts.tz_convert('US/Eastern')
复制代码

1. 使用适当的重采样频率:根据分析需求选择合适的重采样频率。
  1. # 日数据转换为月数据
  2.    monthly = daily.resample('M').sum()
  3.    
  4.    # 日数据转换为周数据
  5.    weekly = daily.resample('W').mean()
复制代码

1. 处理缺失值:时间序列数据中常有缺失值,选择合适的填充方法。
  1. # 前向填充
  2.    ts = ts.fillna(method='ffill')
  3.    
  4.    # 后向填充
  5.    ts = ts.fillna(method='bfill')
  6.    
  7.    # 线性插值
  8.    ts = ts.interpolate()
复制代码

1. 利用滚动窗口计算:使用滚动窗口计算移动统计量,而不是手动计算。
  1. # 计算7天移动平均
  2.    ma_7 = ts.rolling(window=7).mean()
  3.    
  4.    # 计算30天移动标准差
  5.    std_30 = ts.rolling(window=30).std()
复制代码

1. 考虑季节性模式:对于具有明显季节性的数据,使用季节性分解或季节性ARIMA模型。
  1. from statsmodels.tsa.seasonal import seasonal_decompose
  2.    
  3.    # 分解时间序列
  4.    decomposition = seasonal_decompose(ts, model='additive', period=12)
复制代码

1. 可视化时间序列数据:使用适当的可视化方法探索和展示时间序列数据。
  1. import matplotlib.pyplot as plt
  2.    
  3.    plt.figure(figsize=(12, 6))
  4.    ts.plot()
  5.    plt.title('Time Series Data')
  6.    plt.xlabel('Date')
  7.    plt.ylabel('Value')
  8.    plt.show()
复制代码

1.
  1. 文档化日期处理逻辑:在代码中添加注释,解释日期处理的逻辑和假设。# 将日期字符串转换为datetime对象,假设输入格式为YYYY-MM-DD
  2. df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
  3. # 计算同比增长率,假设数据是月度数据
  4. yoy_growth = df['value'].pct_change(12) * 100
复制代码

文档化日期处理逻辑:在代码中添加注释,解释日期处理的逻辑和假设。
  1. # 将日期字符串转换为datetime对象,假设输入格式为YYYY-MM-DD
  2. df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
  3. # 计算同比增长率,假设数据是月度数据
  4. yoy_growth = df['value'].pct_change(12) * 100
复制代码

通过掌握这些技巧和最佳实践,您可以更高效地处理时间序列数据,从基础的数据清洗和格式化到高级的分析和预测,充分发挥Pandas在日期时间处理方面的强大功能。
回复

使用道具 举报

0

主题

638

科技点

433

积分

候风辨气

积分
433
发表于 2025-10-3 13:10:01 | 显示全部楼层
感謝分享
温馨提示:看帖回帖是一种美德,您的每一次发帖、回帖都是对论坛最大的支持,谢谢! [这是默认签名,点我更换签名]
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.