mthoutai

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Pandas2.2 Index objects

Time date components

方法描述
DatetimeIndex.year用于获取 DatetimeIndex 中每个日期时间元素的年份部分
DatetimeIndex.month用于获取 DatetimeIndex 中每个日期时间元素的月份部分
DatetimeIndex.day用于获取 DatetimeIndex 中每个日期时间元素的日期部分(月份中的第几天)
DatetimeIndex.hour用于获取 DatetimeIndex 中每个日期时间元素的小时部分
DatetimeIndex.minute用于获取 DatetimeIndex 中每个日期时间元素的分钟部分
DatetimeIndex.second用于获取 DatetimeIndex 中每个日期时间元素的秒部分
DatetimeIndex.microsecond用于获取 DatetimeIndex 中每个日期时间元素的微秒部分
DatetimeIndex.nanosecond用于获取时间戳中的纳秒部分(0-999999999)
DatetimeIndex.date用于获取时间戳中的日期部分(年-月-日)
DatetimeIndex.time用于获取时间戳中的时间部分(时:分:秒)
DatetimeIndex.timetz用于获取带有时区信息的时间部分(时:分:秒)
DatetimeIndex.dayofyear用于获取时间戳在一年中的天数序号
DatetimeIndex.day_of_year用于获取每个日期在一年中的序号
DatetimeIndex.dayofweek用于获取时间戳在一周中的星期几
DatetimeIndex.day_of_week用于获取时间戳在一周中的星期几
DatetimeIndex.weekday用于获取时间戳在一周中的星期几
DatetimeIndex.quarter用于获取时间戳在一年中的季度信息
DatetimeIndex.tz用于获取时间戳的时区信息
DatetimeIndex.freq用于获取时间序列的频率信息
DatetimeIndex.freqstr用于获取时间序列频率的字符串表示

pandas.DatetimeIndex.freqstr 属性详解

pandas.DatetimeIndex.freqstr 是 DatetimeIndex 对象的一个属性,用于获取时间序列频率的字符串表示。它是 [freq] 属性的字符串形式,提供了对时间序列频率的可读描述。

属性说明
  • 用途:获取 DatetimeIndex 中时间序列频率的字符串表示
  • 类型:只读属性
  • 返回值
    • 如果 DatetimeIndex 有规律的频率,返回对应的频率字符串
    • 如果 DatetimeIndex 没有规律频率,返回 None
示例代码及结果
示例 1: 基本用法
import pandas as pd
# 创建有规律频率的 DatetimeIndex
dates_with_freq = pd.date_range('2023-01-01', periods=10, freq='D')
print("有规律频率的 DatetimeIndex:")
print(dates_with_freq)
print("频率对象:", dates_with_freq.freq)
print("频率字符串:", dates_with_freq.freqstr)
# 创建无规律频率的 DatetimeIndex
dates_without_freq = pd.DatetimeIndex(['2023-01-01', '2023-01-03', '2023-01-07', '2023-01-15'])
print("\n无规律频率的 DatetimeIndex:")
print(dates_without_freq)
print("频率对象:", dates_without_freq.freq)
print("频率字符串:", dates_without_freq.freqstr)

输出结果:

有规律频率的 DatetimeIndex:
DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04',
               '2023-01-05', '2023-01-06', '2023-01-07', '2023-01-08',
               '2023-01-09', '2023-01-10'],
              dtype='datetime64[ns]', freq='D')
频率对象: 
频率字符串: D
无规律频率的 DatetimeIndex:
DatetimeIndex(['2023-01-01', '2023-01-03', '2023-01-07', '2023-01-15'], dtype='datetime64[ns]', freq=None)
频率对象: None
频率字符串: None
示例 2: 不同频率字符串的比较
import pandas as pd
# 创建不同频率的 DatetimeIndex
daily_dates = pd.date_range('2023-01-01', periods=5, freq='D')
hourly_dates = pd.date_range('2023-01-01', periods=5, freq='H')
monthly_dates = pd.date_range('2023-01-01', periods=5, freq='M')
weekly_dates = pd.date_range('2023-01-01', periods=5, freq='W')
business_days = pd.date_range('2023-01-01', periods=5, freq='B')
print("每日频率:")
print(daily_dates)
print("频率字符串:", daily_dates.freqstr)
print("\n每小时频率:")
print(hourly_dates)
print("频率字符串:", hourly_dates.freqstr)
print("\n每月频率:")
print(monthly_dates)
print("频率字符串:", monthly_dates.freqstr)
print("\n每周频率:")
print(weekly_dates)
print("频率字符串:", weekly_dates.freqstr)
print("\n工作日频率:")
print(business_days)
print("频率字符串:", business_days.freqstr)

输出结果:

每日频率:
DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04',
               '2023-01-05'],
              dtype='datetime64[ns]', freq='D')
频率字符串: D
每小时频率:
DatetimeIndex(['2023-01-01 00:00:00', '2023-01-01 01:00:00',
               '2023-01-01 02:00:00', '2023-01-01 03:00:00',
               '2023-01-01 04:00:00'],
              dtype='datetime64[ns]', freq='H')
频率字符串: H
每月频率:
DatetimeIndex(['2023-01-31', '2023-02-28', '2023-03-31', '2023-04-30',
               '2023-05-31'],
              dtype='datetime64[ns]', freq='M')
频率字符串: M
每周频率:
DatetimeIndex(['2023-01-01', '2023-01-08', '2023-01-15', '2023-01-22',
               '2023-01-29'],
              dtype='datetime64[ns]', freq='W-SUN')
频率字符串: W-SUN
工作日频率:
DatetimeIndex(['2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05',
               '2023-01-06'],
              dtype='datetime64[ns]', freq='B')
频率字符串: B
示例 3: 复合频率字符串
import pandas as pd
# 创建复合频率的 DatetimeIndex
every_3_days = pd.date_range('2023-01-01', periods=5, freq='3D')
twice_daily = pd.date_range('2023-01-01', periods=6, freq='12H')
every_15_minutes = pd.date_range('2023-01-01', periods=5, freq='15T')
print("每3天频率:")
print(every_3_days)
print("频率字符串:", every_3_days.freqstr)
print("\n每12小时频率:")
print(twice_daily)
print("频率字符串:", twice_daily.freqstr)
print("\n每15分钟频率:")
print(every_15_minutes)
print("频率字符串:", every_15_minutes.freqstr)

输出结果:

每3天频率:
DatetimeIndex(['2023-01-01', '2023-01-04', '2023-01-07', '2023-01-10',
               '2023-01-13'],
              dtype='datetime64[ns]', freq='3D')
频率字符串: 3D
每12小时频率:
DatetimeIndex(['2023-01-01 00:00:00', '2023-01-01 12:00:00',
               '2023-01-02 00:00:00', '2023-01-02 12:00:00',
               '2023-01-03 00:00:00', '2023-01-03 12:00:00'],
              dtype='datetime64[ns]', freq='12H')
频率字符串: 12H
每15分钟频率:
DatetimeIndex(['2023-01-01 00:00:00', '2023-01-01 00:15:00',
               '2023-01-01 00:30:00', '2023-01-01 00:45:00',
               '2023-01-01 01:00:00'],
              dtype='datetime64[ns]', freq='15T')
频率字符串: 15T
示例 4: 与时区结合使用
import pandas as pd
# 创建带时区的有规律频率 DatetimeIndex
tz_dates = pd.date_range('2023-01-01', periods=5, freq='D', tz='UTC')
print("带时区的有规律频率 DatetimeIndex:")
print(tz_dates)
print("频率对象:", tz_dates.freq)
print("频率字符串:", tz_dates.freqstr)
# 创建带时区的无规律频率 DatetimeIndex
tz_irregular = pd.DatetimeIndex([
'2023-01-01 12:00:00',
'2023-01-03 12:00:00',
'2023-01-07 12:00:00'
], tz='UTC')
print("\n带时区的无规律频率 DatetimeIndex:")
print(tz_irregular)
print("频率对象:", tz_irregular.freq)
print("频率字符串:", tz_irregular.freqstr)

输出结果:

带时区的有规律频率 DatetimeIndex:
DatetimeIndex(['2023-01-01 00:00:00+00:00', '2023-01-02 00:00:00+00:00',
               '2023-01-03 00:00:00+00:00', '2023-01-04 00:00:00+00:00',
               '2023-01-05 00:00:00+00:00'],
              dtype='datetime64[ns, UTC]', freq='D')
频率对象: 
频率字符串: D
带时区的无规律频率 DatetimeIndex:
DatetimeIndex(['2023-01-01 12:00:00+00:00', '2023-01-03 12:00:00+00:00',
               '2023-01-07 12:00:00+00:00'],
              dtype='datetime64[ns, UTC]', freq=None)
频率对象: None
频率字符串: None
示例 5: 在数据分析中的应用
import pandas as pd
import numpy as np
# 创建有规律频率的时间序列数据
dates = pd.date_range('2023-01-01', '2023-12-31', freq='D')
data = pd.Series(np.random.randn(len(dates)), index=dates, name='daily_data')
print("时间序列数据:")
print(f"数据点数量: {len(data)}")
print(f"起始日期: {data.index.min()}")
print(f"结束日期: {data.index.max()}")
print(f"频率对象: {data.index.freq}")
print(f"频率字符串: {data.index.freqstr}")
# 检查频率是否规则
print(f"\n是否有规律频率: {data.index.freq is not None}")
print(f"频率字符串是否为None: {data.index.freqstr is not None}")
# 创建不规则时间序列进行对比
irregular_dates = pd.DatetimeIndex([
'2023-01-01', '2023-01-03', '2023-01-07', '2023-01-15', '2023-01-25'
])
irregular_data = pd.Series(np.random.randn(len(irregular_dates)), index=irregular_dates, name='irregular_data')
print("\n不规则时间序列数据:")
print(f"数据点数量: {len(irregular_data)}")
print(f"频率对象: {irregular_data.index.freq}")
print(f"频率字符串: {irregular_data.index.freqstr}")
print(f"是否有规律频率: {irregular_data.index.freq is not None}")

输出结果:

时间序列数据:
数据点数量: 365
起始日期: 2023-01-01 00:00:00
结束日期: 2023-12-31 00:00:00
频率对象: 
频率字符串: D
是否有规律频率: True
频率字符串是否为None: True
不规则时间序列数据:
数据点数量: 5
频率对象: None
频率字符串: None
是否有规律频率: False
示例 6: 空 DatetimeIndex 处理
import pandas as pd
# 创建空的有频率 DatetimeIndex
empty_with_freq = pd.DatetimeIndex([], freq='D')
print("空的有频率 DatetimeIndex:")
print(empty_with_freq)
print("频率对象:", empty_with_freq.freq)
print("频率字符串:", empty_with_freq.freqstr)
# 创建空的无频率 DatetimeIndex
empty_without_freq = pd.DatetimeIndex([])
print("\n空的无频率 DatetimeIndex:")
print(empty_without_freq)
print("频率对象:", empty_without_freq.freq)
print("频率字符串:", empty_without_freq.freqstr)

输出结果:

空的有频率 DatetimeIndex:
DatetimeIndex([], dtype='datetime64[ns]', freq='D')
频率对象: 
频率字符串: D
空的无频率 DatetimeIndex:
DatetimeIndex([], dtype='datetime64[ns]', freq=None)
频率对象: None
频率字符串: None
示例 7: 频率字符串的实际应用
import pandas as pd
# 创建多个不同频率的时间序列
frequencies = ['D', 'H', 'M', 'W', 'B', '3D', '12H', '15T']
series_dict = {}
for freq in frequencies:
if freq in ['D', 'H', 'M', 'W', 'B']:
dates = pd.date_range('2023-01-01', periods=10, freq=freq)
else:
dates = pd.date_range('2023-01-01', periods=5, freq=freq)
series_dict[freq] = pd.Series(range(len(dates)), index=dates)
# 显示所有时间序列的频率信息
print("不同频率时间序列的频率字符串:")
print("-" * 40)
for freq_code, series in series_dict.items():
print(f"频率代码: {freq_code:4s} | 频率字符串: {series.index.freqstr:8s} | 数据点数: {len(series)}")

输出结果:

不同频率时间序列的频率字符串:
----------------------------------------
频率代码: D    | 频率字符串: D        | 数据点数: 10
频率代码: H    | 频率字符串: H        | 数据点数: 10
频率代码: M    | 频率字符串: M        | 数据点数: 10
频率代码: W    | 频率字符串: W-SUN    | 数据点数: 10
频率代码: B    | 频率字符串: B        | 数据点数: 10
频率代码: 3D   | 频率字符串: 3D       | 数据点数: 5
频率代码: 12H  | 频率字符串: 12H      | 数据点数: 5
频率代码: 15T  | 频率字符串: 15T      | 数据点数: 5
应用场景
  1. 时间序列分析:快速识别时间序列的采样频率
  2. 数据验证:验证时间序列数据的频率一致性
  3. 报告生成:在报告中显示时间序列的频率信息
  4. 数据处理:根据频率字符串选择合适的数据处理方法
  5. 用户界面:在图形界面中显示友好的频率描述
  6. 配置管理:保存和恢复时间序列的频率设置
注意事项
  • freqstr 是只读属性,不能直接修改
  • 对于有规律频率的 DatetimeIndex,freqstr 返回频率的字符串表示
  • 对于无规律频率的 DatetimeIndex,freqstr 返回 None
  • freqstr 与 [freq] 属性相关联,但提供的是字符串形式
  • 频率字符串对于用户更友好,便于理解和显示
  • 可以通过 pd.date_range() 创建具有特定频率字符串的 DatetimeIndex

通过 freqstr 属性,我们可以方便地获取 DatetimeIndex 频率的字符串表示,这对于时间序列数据的分析、显示和处理非常有用。

posted on 2025-11-06 20:03  mthoutai  阅读(19)  评论(0)    收藏  举报