在Pandas中按日期时间条件筛选行最优雅且最具Python风格的方法是什么?
Pandas 日期时间类型数据的行筛选方法
1. 直接比较日期值
- 先确认目标列是datetime类型,若不是先转换:
df['date_col'] = pd.to_datetime(df['date_col']) - 筛选指定日期之后的数据:
df[df['date_col'] > '2023-06-01'] - 筛选日期区间内的数据:
df[(df['date_col'] >= '2023-01-01') & (df['date_col'] <= '2023-12-31')]
2. 提取日期分量筛选
借助datetime列的dt属性,可提取年、月、日等维度进行筛选:
- 筛选2023年的数据:
df[df['date_col'].dt.year == 2023] - 筛选10月份的数据:
df[df['date_col'].dt.month == 10] - 筛选周末数据:
df[df['date_col'].dt.dayofweek >= 5](注:dayofweek以0代表周一,6代表周日) - 筛选每月第一天的数据:
df[df['date_col'].dt.day == 1]
3. 索引切片筛选(适用于DatetimeIndex)
将日期列设为索引后,用切片语法更简洁:
- 设置日期索引:
df = df.set_index('date_col') - 筛选2023年7月的所有数据:
df['2023-07'] - 筛选2023年7月1日至15日的数据:
df['2023-07-01':'2023-07-15']
4. 用between()简化区间筛选
用between()方法快速指定日期范围:
- 筛选2023年6月全月数据:
df[df['date_col'].between('2023-06-01', '2023-06-30')] - 忽略时间部分,仅按日期筛选:
df[df['date_col'].dt.date.between(datetime.date(2023,6,1), datetime.date(2023,6,30))](需提前导入import datetime)
内容的提问来源于stack exchange,提问作者Moher
相关产品推荐
相关产品推荐

