python - Pandas 有效地重新索引和插值时间序列(重新索引丢弃数据)
问题描述
假设我希望通过线性插值将时间序列重新索引为预定义的索引,其中没有一个索引值在新旧索引之间共享。例如
# index is all precise timestamps e.g. 2018-10-08 05:23:07
series = pandas.Series(data,index)
# I want rounded date-times
desired_index = pandas.date_range("2010-10-08",periods=10,freq="30min")
教程/API 建议执行此操作的方法是reindex
使用interpolate
. 但是,由于新旧索引之间没有日期时间重叠,reindex 输出所有 NaN:
# The following outputs all NaN as no date times match old to new index
series.reindex(desired_index)
我不想在此期间填充最接近的值,reindex
因为那样会失去精度,所以我想出了以下内容;在插值之前将重新索引的系列与原始系列连接起来:
pandas.concat([series,series.reindex(desired_index)]).sort_index().interpolate(method="linear")
这似乎非常低效,将两个系列连接起来然后排序。有没有更好的办法?
解决方案
我能看到的唯一(简单)方法是使用重新采样来上采样到您的时间分辨率(比如 1 秒),然后重新索引。
获取示例 DataFrame:
import numpy as np
import pandas as pd
np.random.seed(2)
df = (pd.DataFrame()
.assign(SampleTime=pd.date_range(start='2018-10-01', end='2018-10-08', freq='30T')
+ pd.to_timedelta(np.random.randint(-5, 5, size=337), unit='s'),
Value=np.random.randn(337)
)
.set_index(['SampleTime'])
)
让我们看看数据是什么样的:
df.head()
Value
SampleTime
2018-10-01 00:00:03 0.033171
2018-10-01 00:30:03 0.481966
2018-10-01 01:00:01 -0.495496
获取所需的索引:
desired_index = pd.date_range('2018-10-01', periods=10, freq='30T')
现在,使用所需索引和现有索引的并集重新索引数据,根据时间进行插值,并仅使用所需索引再次重新索引:
(df
.reindex(df.index.union(desired_index))
.interpolate(method='time')
.reindex(desired_index)
)
Value
2018-10-01 00:00:00 NaN
2018-10-01 00:30:00 0.481218
2018-10-01 01:00:00 -0.494952
2018-10-01 01:30:00 -0.103270
如您所见,第一个时间戳仍然存在问题,因为它超出了原始索引的范围;有很多方法可以解决这个问题(pad
例如)。
推荐阅读
- sql - 具有两个匹配结果的 SQL Server MERGE
- javascript - 如何在javascript中引用目录
- vb.net - 检查泛型类
- vba - VBA 宏:将工作表从一个 Excel 文件复制到另一个
- file-upload - 使用节点中的大型媒体文件一次发出多个发布请求时的内存问题
- c# - C# - 当用户滚动到富文本框的底部时如何显示一个复选框
- excel - 如何在 Excel 中将月份数字(即“12”)转换为月份名称?
- git - 清理 git 历史上的“WIP 和索引”
- bots - 制作机器人来填写 Troops.ai 对话框以更新销售人员记录,如何让我的机器人填写部队对话框?
- python - 即使存在于 locals() 中也没有定义 python 函数