【问题标题】:python piecewise linear interpolation across dataframes in a list跨列表中数据帧的python分段线性插值
【发布时间】:2023-02-10 13:34:26
【问题描述】:

我正在尝试应用分段线性插值。我首先尝试使用 pandas 内置的插值函数,但它没有用。

示例数据如下所示

import pandas as pd
import numpy as np

d = {'ID':[5,5,5,5,5,5,5], 'month':[0,3,6,9,12,15,18], 'num':[7,np.nan,5,np.nan,np.nan,5,8]}
tempo = pd.DataFrame(data = d)
d2 = {'ID':[6,6,6,6,6,6,6], 'month':[0,3,6,9,12,15,18], 'num':[5,np.nan,2,np.nan,np.nan,np.nan,7]}
tempo2 = pd.DataFrame(data = d2)
this = []
this.append(tempo)
this.append(tempo2)

实际数据有超过 1000 个唯一 ID,因此我将每个 ID 过滤到数据框中并将它们放入列表中。

列表中的第一个数据框如下所示

我正在尝试遍历列表中的所有数据框以进行分段线性插值。我试图将月份更改为索引并使用 .interpolate(method='index', inplace = True) 但它不起作用。

预期的输出是

编号 |月 |数

5 | 0 | 7

5 | 3 | 6个

5 | 6 | 5个

5 | 9 | 5个

5 | 12 | 5个

5 | 15 | 5个

5 | 18 | 8个

这需要应用于列表中的所有数据框。

我真的很感激任何帮助!谢谢。

【问题讨论】:

    标签: python pandas dataframe numpy


    【解决方案1】:

    假设这是您之前问题的跟进,请将代码更改为:

    for i, df in enumerate(this):
        this[i] = (df
            .set_index('month')
            .reindex(range(df['month'].min(), df['month'].max()+3, 3))
            .interpolate()
            .reset_index()[df.columns]
            )
    

    输出:

    
    [   ID  month  num
    0   5      0  7.0
    1   5      3  6.0
    2   5      6  5.0
    3   5      9  5.0
    4   5     12  5.0
    5   5     15  5.0
    6   5     18  8.0,
       ID  month   num
    0   6      0  5.00
    1   6      3  3.50
    2   6      6  2.00
    3   6      9  3.25
    4   6     12  4.50
    5   6     15  5.75
    6   6     18  7.00]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多