python - 将时间戳转换为 Pandas 中的自定义周期之一

标签 python pandas time-series

假设我为一天定义了 4 个自定义时间段:早上 6 点到中午 12 点、中午 12 点到晚上 7 点、晚上 7 点到凌晨 00 点、早上 00 点到早上 6 点。 pandas 中将给定时间戳转换为这些期间之一的简洁方法是什么?

最佳答案

也许你可以使用numpy.searchsorted:

>>> idx
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-08-26 22:20:34.580486, ..., 2014-08-29 05:20:34.581053]
Length: 12, Freq: None, Timezone: None
>>> idx.hour
array([22,  3,  8, 13, 18, 23,  4,  9, 14, 19,  0,  5], dtype=int32)

>>> p = np.array(['00am-06am', '06am-12pm', '12pm-07pm', '07pm-00am'])
>>> p[np.searchsorted([6, 12, 19, 24], idx.hour)]
array(['07pm-00am', '00am-06am', '06am-12pm', '12pm-07pm', '12pm-07pm',
       '07pm-00am', '00am-06am', '06am-12pm', '12pm-07pm', '12pm-07pm',
       '00am-06am', '00am-06am'], 
      dtype='<U9')

关于python - 将时间戳转换为 Pandas 中的自定义周期之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25517830/

相关文章:

python - Django 正则表达式验证器不工作 - 错误 500 部署服务器

python - 如何在贪吃蛇游戏中为蛇的 body 部位使用不同的图像? (Python、Pygame、蛇)

python - 按特定顺序在 Pandas 中取消堆叠 Dataframe

python pandas 创建数据框并强制使用多种列类型

python - 使用 tf.eager 训练复杂的 nn 模型(使用 TF2 符号支持效果更好)

python - 从字典中的值列表创建矩阵

python - 从 timedelta 构建 Pandas pd.tseries.offsets

Python 的 Pandas 为 DatetimeIndex 提供了错误的工作日索引

time-series - Apache Kudu vs InfluxDB 在时间序列数据上的快速分析

datetime - 从频率 = 23 的不规则 (as.Date) 时间序列创建规则时间序列