【问题标题】:How to do a linear interpolation in pandas taking values of X into account?如何在考虑 X 值的情况下在 pandas 中进行线性插值?
【发布时间】:2020-01-30 18:54:35
【问题描述】:

我有一个包含两列的数据框:XYY 中的某些值缺失 (np.nan)。

我想使用线性插值填充NaNs。更详细地说,我想按X 对数据帧进行排序,Y 的任何缺失值都应该是Y 的两个相邻值的“线性混合”(一个对应于较小的X,另一个对应于另一个到更大的X)。

如果缺少的Y对应的X的值更接近两个X和可用Y之一,那么Y的填充值应该接近对应的Y .如何在 pandas 中高效优雅地做到这一点?

请注意,据我所知,pandas.Series.interpolate 不能满足我的需求。

【问题讨论】:

    标签: python pandas interpolation


    【解决方案1】:

    设置数据框:

    x = [0,1,3,4,7,9,11,122,123,128]
    y = [2,8,12,np.NaN, 22, 31, 34, np.NaN, 43, 48]
    
    df = pd.DataFrame({"x":x, "y":y})
    print(df)
    
         x     y
    0    0   2.0
    1    1   8.0
    2    3  12.0
    3    4   NaN
    4    7  22.0
    5    9  31.0
    6   11  34.0
    7  122   NaN
    8  123  43.0
    9  128  48.0
    

    将列'x'设置为索引:

    df = df.set_index('x')
    

    然后将 interplote 中的方法设置为 'index'。

    df.y = df.y.interpolate(method='index')
    

    这会导致:

    df
    
            y
    x   
    0      2.000000
    1      8.000000
    3     12.000000
    4     14.500000
    7     22.000000
    9     31.000000
    11    34.000000
    122   42.919643
    123   43.000000
    128   48.000000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2023-03-18
      相关资源
      最近更新 更多