python - 优雅的 pandas 使用 date_range 预填充各种可能的频率设置
问题描述
我正在尝试预填充类似于以下内容的数据框:
在示例中,我随机删除了一些行以突出显示挑战。我正在尝试*优雅地计算 dti 值。第一行中的 dti 值将为 0(即使根据脚本删除了第一行),但由于 dti 序列中出现间隙,因此需要跳过丢失的行。一种合乎逻辑的方法是将 dt/delta 相除以创建一个表示存储桶的唯一整数,但我尝试过的任何东西都感觉不到或看起来很优雅。
一些代码来帮助模拟问题:
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
start = datetime.now()
nin = 24
delta='4H'
df = pd.date_range( start, periods=nin, freq=deltadf, name ='dt')
# remove some random data points
frac_points = 8/24 # Fraction of points to retain
r = np.random.rand(nin)
df = df[r <= frac_points] # reduce the number of points
df = df.to_frame(index=False) # reindex
df['dti'] = ...
先感谢您,
解决方案
一种解决方案是将每行之间的时间差除以 timedelta:
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
start = datetime.now()
nin = 24
delta='4H'
df = pd.date_range(start, periods=nin, freq=delta, name='dt')
# Round to nearest ten minutes for better readability
df = df.round('10min')
# Ensure reproducibility
np.random.seed(1)
# remove some random data points
frac_points = 8/24 # Fraction of points to retain
r = np.random.rand(nin)
df = df[r <= frac_points] # reduce the number of points
df = df.to_frame(index=False) # reindex
df['dti'] = df['dt'].diff() / pd.to_timedelta(delta)
df['dti'] = df['dti'].fillna(0).cumsum().astype(int)
df
dt dti
0 2019-03-17 18:10:00 0
1 2019-03-17 22:10:00 1
2 2019-03-18 02:10:00 2
3 2019-03-18 06:10:00 3
4 2019-03-18 10:10:00 4
5 2019-03-19 10:10:00 10
6 2019-03-19 18:10:00 12
7 2019-03-20 10:10:00 16
8 2019-03-20 14:10:00 17
9 2019-03-21 02:10:00 20
推荐阅读
- python - 在python中查找正则表达式
- r - 如何从 r 中的单个数据帧中拆分具有随机子集的数据帧?
- javascript - Javascript:如何创建一个既像对象又像函数的变量?
- pandas - 大熊猫中用于方差分析和回归的分类变量?
- azure - Azure Kubernetes 服务:即使在 CD 管道中添加了 ImagePullSecret,图像提取错误(身份验证)
- laravel - 如何防止用户在浏览器中直接访问路由(后端控制器)?
- python - 使用 pip 在共享主机服务器上安装 mysqlclient 失败
- prolog - prolog 文本处理和构造状态的模板
- javascript - 无法从公共文件夹中获取一组 svg 文件到 React js 中的组件
- sql-loader - 为每个文件生成不同的序列号