在处理时间序列数据时,我们经常需要将不规则或稀疏的数据转换为更规则的频率(例如,从每日数据到每月或每年数据),并填充缺失值。Pandas库提供了强大的resample和interpolate方法来完成此任务。然而,如果不正确使用,尤其是在数据稀疏的情况下,可能会遇到插值结果出现大量NaN值或呈现不自然的线性趋势的问题。
用户面临的问题是,当原始时间序列数据较为稀疏时,直接使用df.resample('1Y').interpolate(method='time')会产生不理想的结果。这并非interpolate(method='time')方法本身的问题,而是其与resample操作结合时的行为特性。
resample的操作机制:resample方法用于将时间序列数据重新采样到指定的频率。例如,df.resample('1Y')会将数据按年份分组。关键在于,如果某个时间段(例如某个年份)在原始数据中没有对应的条目,resample在不指定聚合函数(如mean(), sum(), first()等)的情况下,会为该时间段生成一个包含NaN值的行。这相当于创建了一个新的、可能包含大量缺失值的索引。
interpolate(method='time')的行为:interpolate(method='time')是interpolate(method='linear')在DatetimeIndex上的特例,它会根据时间戳的数值差值进行线性插值。当resample操作引入了大量的NaN值时,interpolate(method='time')会尝试连接这些NaN值两端的有效数据点。如果有效数据点之间的时间跨度非常大(例如,原始数据在2010年和2020年有值,中间年份没有),interpolate将简单地在这些点之间绘制一条直线,导致结果看起来非常线性,并且对于没有有效数据点覆盖的区间,可能仍然保留NaN。
考虑以下用户提供的代码片段,它展示了这种常见问题:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np # 模拟稀疏时间序列数据 # 假设我们只有2010、2015、2020年的数据 data = { 'Date': ['2010-01-01', '2015-06-15', '2020-12-31'], 'Value': [10, 25, 40] } df = pd.DataFrame(data) df['Date'] = pd.to_datetime(df['Date']) df.set_index('Date', inplace=True) # 原始数据可视化 plt.figure(figsize=(10, 6)) sns.scatterplot(data=df, x=df.index, y=df['Value'], s=100, label='Original Data') plt.title('Original Sparse Time Series Data') plt.xlabel('Date') plt.ylabel('Value') plt.grid(True) plt.show() # 用户尝试的插值方法 # df_resampled = df.resample('1Y') # 此时df_resampled是一个Grouper对象,需要聚合 # 错误用法:直接在Grouper对象上调用interpolate会导致错误或不期望的结果 # df_interp = df_resampled.interpolate(method='time') # 正确的理解是:用户可能期望在resample后得到一个DataFrame,然后在其上插值 # 如果不加聚合函数,resample会产生一个DataFrame,其中大部分是NaN df_resampled_no_agg = df.resample('1Y').asfreq() # 使用asfreq()来填充缺失的频率,值为NaN print("Resampled DataFrame (without aggregation, with NaNs):\n", df_resampled_no_agg) # 对包含NaN的DataFrame进行插值 df_interp_problematic = df_resampled_no_agg.interpolate(method='time') print("\nProblematic Interpolated Data (linear between sparse points):\n", df_interp_problematic) # 可视化问题结果 plt.figure(figsize=(10, 6)) sns.scatterplot(data=df, x=df.index, y=df['Value'], s=100, label='Original Data') sns.lineplot(data=df_interp_problematic, x=df_interp_problematic.index, y=df_interp_problematic['Value'], color='red', linestyle='--', marker='o', label='Problematic Interpolation (1Y)') plt.title('Problematic Interpolation: Linear Results from Sparse Data') plt.xlabel('Date') plt.ylabel('Value') plt.grid(True) plt.legend() plt.show()
在上述模拟中,df.resample('1Y').asfreq()会为2010年到2020年之间的每个年份创建一行,但除了2010、2015、2020年之外,其他年份的Value列都将是NaN。随后对这个包含大量NaN的DataFrame进行interpolate(method='time'),就会导致在仅有的几个有效数据点之间进行简单的线性连接。
要获得更合理的时间序列插值结果,我们需要根据数据的特性
以上就是Pandas时间序列插值:避免resample后的线性与NaN结果的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号