Pandas 有效地重新索引和插入时间序列(重新索引删除数据)

Sid*_*Bob 3 python time-series 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") 
Run Code Online (Sandbox Code Playgroud)

教程/API 建议的方法是reindex使用interpolate. 但是,由于新旧索引之间的日期时间没有重叠,因此 reindex 输出所有 NaN:

# The following outputs all NaN as no date times match old to new index
series.reindex(desired_index)
Run Code Online (Sandbox Code Playgroud)

我不想在此期间填充最近的值,reindex因为这会失去精度,所以我想出了以下内容;在插值之前将重新索引的系列与原始系列连接起来:

pandas.concat([series,series.reindex(desired_index)]).sort_index().interpolate(method="linear")
Run Code Online (Sandbox Code Playgroud)

这看起来效率很低,将两个系列串联然后排序。有没有更好的办法?

bad*_*erm 7

我能看到的唯一(简单)方法是使用resample上采样到您的时间分辨率(比如 1 秒),然后重新索引。

获取示例数据帧:

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'])
)
Run Code Online (Sandbox Code Playgroud)

让我们看看数据是什么样的:

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
Run Code Online (Sandbox Code Playgroud)

获取所需的索引:

desired_index = pd.date_range('2018-10-01', periods=10, freq='30T')
Run Code Online (Sandbox Code Playgroud)

现在,使用所需索引和现有索引的并集重新索引数据,根据时间进行插值,然后仅使用所需索引再次重新索引:

(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
Run Code Online (Sandbox Code Playgroud)

如您所见,第一个时间戳仍然存在问题,因为它超出了原始索引的范围;有很多方法可以解决这个问题(pad例如)。