用 pandas 插值数据

问题描述 投票:0回答:1

我有几个测量值,每个值都有一个时间序列。 时间步长分布不均匀,数据系列之间也不均匀。

我尝试使用 Python 和 Pandas 将每个系列插值到固定的 10 秒时间步长,但插值仅为 NaN。

这是截取的数据:

Timestamp,Value
2023-05-20T22:00:04.023Z,102
2023-05-20T22:00:14.033Z,100
2023-05-20T22:00:24.074Z,99
2023-05-20T22:00:35.484Z,99
2023-05-20T22:00:44.029Z,102
2023-05-20T22:00:54.054Z,100
2023-05-20T22:01:04.026Z,99
2023-05-20T22:01:14.029Z,103
2023-05-20T22:01:24.054Z,99
2023-05-20T22:01:34.022Z,98
2023-05-20T22:01:44.026Z,99
2023-05-20T22:01:54.062Z,100
2023-05-20T22:02:04.025Z,125

这是Python脚本。 我想说一切都按要求工作,直到插值方法。

import pandas as pd

Power_curr = pd.read_csv("pathtodata.csv",parse_dates=['Timestamp'])

# Convert the 'Timestamp' column to datetime format
Power_curr['Timestamp'] = pd.to_datetime(Power_curr['Timestamp'])

# timestamp is index
Power_curr.set_index('Timestamp', inplace=True)

# Find start end end, round to 10 s
start_time = Power_curr.index.min().ceil('10s')
end_time = Power_curr.index.max().floor('10s')

# Create new timestamp series
new_time_index = pd.date_range(start=start_time, end=end_time, freq='10s')

# Create new data frame and interpolate into new timestamps
Power_curr_interpolated = Power_curr.reindex(new_time_index).interpolate(method='time')

我认为 Power_curr.reindex(new_time_index) 的结果是问题所在。 它仅返回 NaN 值,因此没有机会对这些值进行插值。但为什么是 NaN?

背景信息:为什么问这个问题?

一个时间序列是一栋房子的用电量,记录在电表上。 另一个时间序列是光伏系统的发电量。 两者都录制了一年多。 有了这些信息,我现在想计算使用电池存储系统可以实现的自给自足程度。

到目前为止做了什么?

  • 我尝试了不同的插值设置,例如“线性”和“最近”

  • 我检查过,new_time_index 的类型正确

    Power_curr['Timestamp'] = pd.to_datetime(Power_curr['Timestamp'])

  • 我检查了安装的pandas版本:v2.2.2

  • 我尝试了

    Power_curr_interpolated = Power_curr['Timestep'].resample('10s').mean() 
    而不是
    Power_curr.reindex(new_time_index).interpolate(method='time')
    。至少没有 NaN,但结果看起来是错误的,因为值不会随着时间戳的改变而改变: pycharm手表

  • 我检查了与此问题相关的其他帖子,如下所示:没有解决方案

  • 还检查了这一点:看起来很有希望 并相信

    Power_curr.reindex(new_time_index)
    的结果就是问题所在。它仅返回 NaN 值,因此没有机会插值任何内容。但为什么呢?

python-3.x pandas time-series linear-interpolation
1个回答
0
投票

问题是重新索引后,您没有剩余数据。因此没有什么可以插入的。

您可以首先添加缺少的索引(同时保留原始索引),然后

interpolate
,然后仅保留所需的索引:

Power_curr_interpolated = (Power_curr
                           .reindex(Power_curr.index.union(new_time_index))
                           .interpolate(method='time')
                           .reindex(new_time_index)
                          )

输出:

                                Value
2023-05-20 22:00:10+00:00  100.805794
2023-05-20 22:00:20+00:00   99.405736
2023-05-20 22:00:30+00:00   99.000000
2023-05-20 22:00:40+00:00  100.585489
2023-05-20 22:00:50+00:00  100.808778
2023-05-20 22:01:00+00:00   99.403730
2023-05-20 22:01:10+00:00  101.388883
2023-05-20 22:01:20+00:00  100.617556
2023-05-20 22:01:30+00:00   98.403491
2023-05-20 22:01:40+00:00   98.597561
2023-05-20 22:01:50+00:00   99.595257
2023-05-20 22:02:00+00:00  114.900130
© www.soinside.com 2019 - 2024. All rights reserved.