首页 > 解决方案 > 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")

这似乎非常低效,将两个系列连接起来然后排序。有没有更好的办法?

标签: pythonpandastime-series

解决方案


我能看到的唯一(简单)方法是使用重新采样来上采样到您的时间分辨率(比如 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例如)。


推荐阅读