python - 以每小时间隔插入 15 分钟的日期时间
问题描述
我有一个包含 3 列的数据框,其中第一列是日期时间。
看起来像这样
Datetime Level1 Level2
2016-02-24 01:00 12 15
2016-02-24 02:00 14 13
2016-02-24 03:00 8 12
现在我想在每小时值之间添加 15 分钟的间隔值。但是,Level1 和 Level2 的值与其前一小时相同。它应该如下所示:
Datetime Level1 Level2
2016-02-24 01:00 12 15
2016-02-24 01:15 12 15
2016-02-24 01:30 12 15
2016-02-24 01:45 12 15
2016-02-24 02:00 14 13
2016-02-24 02:15 14 13
2016-02-24 02:30 14 13
2016-02-24 02:45 14 13
2016-02-24 03:00 8 12
2016-02-24 03:15 8 12
2016-02-24 03:30 8 12
2016-02-24 03:45 8 12
我想不出如何正确地做到这一点。
解决方案
将日期时间设置为索引(在转换为日期时间之后),并使用带有前向填充的 asfreq 方法用以前的值填充空值:
#thanks to @a_guest for the cleaned sample data
df = pd.DataFrame(
data=[['2016-02-24 01:00', 12, 15],
['2016-02-24 02:00', 14, 13],
['2016-02-24 03:00', 8, 12]],
columns=['Datetime', 'Level1', 'Level2']
)
df['Datetime'] = pd.to_datetime(df['Datetime'])
df = df.set_index('Datetime')
df.asfreq('15min',method='pad')
Level1 Level2
Datetime
2016-02-24 01:00:00 12 15
2016-02-24 01:15:00 12 15
2016-02-24 01:30:00 12 15
2016-02-24 01:45:00 12 15
2016-02-24 02:00:00 14 13
2016-02-24 02:15:00 14 13
2016-02-24 02:30:00 14 13
2016-02-24 02:45:00 14 13
2016-02-24 03:00:00 8 12
注意:您的问题说时间间隔为 15 分钟,您的最新时间是下午 3 点,而不是下午 4 点,正如您的数据中共享的那样。
推荐阅读
- java - 应用程序因按下按钮而停止?
- html - 如何修复隐藏在 SVG 对象中的 DIV?
- swift - 使用 LocationManager 时最小化对我的服务器发出的 HTTP 请求
- javascript - 创建一个尽可能像对象一样行为的对象代理
- java - 将 OpenCv Mat 对象从 Java 传递到 C Native
- r - 无法为向量分配内存
- c# - 计算 Splay 树中的总和范围
- ruby-on-rails - 从复选框更新嵌套模型中的多条记录
- django - 我想在 Django 中注释新列“is_like”
- python - Python 的 input() 或 raw_input() 重定向到 stderr 而不是 stdout