如何基于DatetimeIndex的时间区间为Pandas DataFrame设置单元格值
问题描述
需要在Pandas DataFrame中基于DatetimeIndex的时分区间创建新列:
- 10:00至11:00(含10:00,不含11:00)赋值为0
- 11:00至12:00(含11:00,不含12:00)赋值为1
现有DataFrame:
DatetimeIndex col_1 2020-07-10 10:00:00+00:00 A 2020-07-10 10:30:00+00:00 B 2020-07-10 11:00:00+00:00 C 2020-07-10 11:30:00+00:00 D 2020-07-11 10:00:00+00:00 E 2020-07-11 10:30:00+00:00 F 2020-07-11 11:00:00+00:00 G 2020-07-11 11:30:00+00:00 H
期望结果:
DatetimeIndex col_1 col_2 2020-07-10 10:00:00+00:00 A 0 2020-07-10 10:30:00+00:00 B 0 2020-07-10 11:00:00+00:00 C 1 2020-07-10 11:30:00+00:00 D 1 2020-07-11 10:00:00+00:00 E 0 2020-07-11 10:30:00+00:00 F 0 2020-07-11 11:00:00+00:00 G 1 2020-07-11 11:30:00+00:00 H 1
尝试过pandas.between_time()和pandas.indexer_between_time()未成功,后续提取时间列后用时间比较出现类型不匹配错误:
start_1 = pd.to_datetime('10:00:00') end_1 = pd.to_datetime('10:59:00') df['group_id'] = ['group_1' if start_1 < t < end_1 else '99' for t in df.time]
错误信息:
'<' not supported between instances of 'Timestamp' and 'datetime.time'
解决方案
方法1:直接提取小时判断
利用DatetimeIndex的hour属性,结合np.where快速赋值:
import numpy as np import pandas as pd df['col_2'] = np.where(df.index.hour == 10, 0, 1)
此方法完全匹配需求:10点区间的行赋值0,11点区间的行赋值1。
方法2:使用between_time索引赋值
先初始化新列为默认值,再通过between_time筛选目标区间修改值:
df['col_2'] = 1 # 默认给11点区间的值 # 筛选10:00到10:59:59的行,赋值为0 df.loc[df.index.between_time('10:00', '10:59:59'), 'col_2'] = 0
between_time包含边界,用10:59:59确保11:00的行不会被误包含。
方法3:统一时间类型后比较
如果要保留提取时间列的方式,需将比较的时间转换为datetime.time类型:
from datetime import time import numpy as np start_1 = time(10, 0, 0) end_1 = time(10, 59, 59) df['col_2'] = np.where((df['time'] >= start_1) & (df['time'] <= end_1), 0, 1)
统一类型后即可避免类型不匹配的错误。
内容的提问来源于stack exchange,提问作者AjWinston
相关产品推荐
相关产品推荐

