看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)用 pd.DatetimeIndex()
创建 1 小时粒度、共 5 条的时间序列,然后分别用切片和 truncate()
截取中间段。
源数据如下:
import pandas as pd
idx = pd.DatetimeIndex(['2023-09-01 08:00','2023-09-01 09:00',
'2023-09-01 10:00','2023-09-01 11:00',
'2023-09-01 12:00'])
s = pd.Series([10,20,30,40,50], index=idx)
print(s)
输出:
2023-09-01 08:00:00 10
2023-09-01 09:00:00 20
2023-09-01 10:00:00 30
2023-09-01 11:00:00 40
2023-09-01 12:00:00 50
dtype: int64
要求:
truncate()
同样截取 09:00 到 11:00。代码如下:
# 1. 切片
s['2023-09-01 09:00':'2023-09-01 11:00']
'''
2023-09-01 09:00:00 20
2023-09-01 10:00:00 30
2023-09-01 11:00:00 40
dtype: int64
'''
# 2. truncate
s.truncate(before='2023-09-01 09:00', after='2023-09-01 11:00')
'''
2023-09-01 09:00:00 20
2023-09-01 10:00:00 30
2023-09-01 11:00:00 40
dtype: int64
'''
DatetimeIndex
支持字符串切片,左闭右闭;truncate()
通过 before/after
参数同样返回左闭右闭区间,两者均基于单调日期索引快速截取时段,无需显式布尔过滤。
(完)
更新时间:2025-09-14 11:33:10 标签:pandas python 时间类型 时间筛选