【发布时间】:2021-07-02 04:46:38
【问题描述】:
我正在使用 Pandas 及时插值数据点,但是在重新采样和插值时,使用不同的重采样率时,对于相同的插值时间,我会得到不同的结果。
这是一个测试示例:
import pandas as pd
import datetime
data = pd.DataFrame({'time': list(map(lambda a: datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S'),
['2021-03-28 12:00:00', '2021-03-28 12:01:40',
'2021-03-28 12:03:20', '2021-03-28 12:05:00',
'2021-03-28 12:06:40', '2021-03-28 12:08:20',
'2021-03-28 12:10:00', '2021-03-28 12:11:40',
'2021-03-28 12:13:20', '2021-03-28 12:15:00'])),
'latitude': [44.0, 44.00463175663968, 44.00919766508212,
44.01357245844425, 44.0176360866699, 44.02127701531401,
44.02439529286458, 44.02690530159084, 44.02873811544965,
44.02984339933479],
'longitude': [-62.75, -62.74998054893869, -62.748902164559304,
-62.74679419470262, -62.7437142666763, -62.739746727555016,
-62.735000345048086, -62.72960533041183, -62.72370976436673,
-62.717475524320704]})
data.set_index('time', inplace=True)
a = data.resample('20s').interpolate(method='time')
b = data.resample('60s').interpolate(method='time')
print(a.iloc[:18:3])
print(b.iloc[:6])
# --- OUTPUT --- #
latitude longitude
time
2021-03-28 12:00:00 44.000000 -62.750000
2021-03-28 12:01:00 44.002779 -62.749988 # <-- Different Values
2021-03-28 12:02:00 44.005545 -62.749765 # <-- Different Values
2021-03-28 12:03:00 44.008284 -62.749118 # <-- Different Values
2021-03-28 12:04:00 44.010948 -62.748059 # <-- Different Values
2021-03-28 12:05:00 44.013572 -62.746794
latitude longitude
time
2021-03-28 12:00:00 44.000000 -62.750000
2021-03-28 12:01:00 44.002714 -62.749359 # <-- Different Values
2021-03-28 12:02:00 44.005429 -62.748718 # <-- Different Values
2021-03-28 12:03:00 44.008143 -62.748077 # <-- Different Values
2021-03-28 12:04:00 44.010858 -62.747435 # <-- Different Values
2021-03-28 12:05:00 44.013572 -62.746794
a 数据帧和b 数据帧应该在每分钟预测相同的值,但在大多数情况下,它们此时会有所不同。
有人知道是什么原因造成的吗?在绘制完整结果时,似乎在分钟内重新采样会导致 Pandas 忽略不在分钟内的时间戳中的数据(例如 12:01:40 和 12:03:20)。
【问题讨论】:
-
比较
data.resample('60s').asfreq()和data.resample('20s').asfreq()以查看哪些点用于插值。您的所有输入样本都适合 20 年代的网格,但只有少数点适合 60 年代的网格。 -
也许我只是错误地使用了这些工具。我希望它使用 all 的数据分别上采样到 20s 和 60s。有没有办法告诉 Pandas 在特定时间间隔重新采样,但也根据原始数据帧插入当时的数据?线性插值现在对我来说“足够好”了。
-
我不会责怪你错误地使用了这些工具——如果你问我,这并不明显发生了什么!我认为option #1 here 可以解决问题 - 重新索引和插值而不是重新采样。
numpy.interp也可用作 shown here。 -
成功了!非常感谢您的帮助:) 如果您将此作为答案发布,我将接受它以供其他人快速查看。
标签: python-3.x pandas interpolation python-datetime pandas-resample