【问题标题】:How to replace a value in a pandas df with an interpolation如何用插值替换熊猫df中的值
【发布时间】:2021-11-10 15:08:44
【问题描述】:

我有一个数据框 df,看起来像这样

print(df)
x     outlier_flag
10    1
NaN   1
30    1
543  -1
50    1

我想用row['A][i-1]row['A][i+1] 之间的插值替换标有outlier_flag==-1 的值,这意味着我想用40 替换显示的错误值543。

我能做的是

df['x'] = df.apply(lambda row: np.nan if row['outlier_flag']==-1 else row['x'], axis=1)
df.interpolate(method='polynomial', order=3, inplace=True)

但我不想这样做,因为这也会在df['x'] 中插入未标记outlier_flag==-1nan 值(请参阅第二行)!纯nan 值,未标记标志,我想保留为nan 用于稍后的任务。

那么,有没有办法进行适当的插值,即使对于像 543 这样不是 nan 的值?

我试过了

df['x'] = df.apply(lambda row: row['x'].interpolate(method='polynomial', order=3) if row['outlier_flag']==-1 else row['x'], axis=1)

但这会引发错误,因为只有nan 可以被插值,而543int。你对我有什么建议吗?天呐

【问题讨论】:

    标签: python pandas dataframe interpolation outliers


    【解决方案1】:

    这是一种您可以按照自己的意愿使用interpolate() 的方式。

    您可以先创建一个列表,其中包含异常标志中具有 -1 的行的索引,然后使用 loc 将 x 中的值替换为 np.nan

    incl = df.index[df['outlier_flag'] == -1].tolist()
    df.loc[df.index.isin(incl), 'x'] = np.nan
    
    >>> df
          x  outlier_flag
    0  10.0             1
    1   NaN             1
    2  30.0             1
    3   NaN            -1
    4  50.0             1
    

    然后,您可以使用 np.where 检查 x isnull() 是否以及该特定索引是否在您创建的列表中,并应用您的插值:

    df['x']= np.where( (df['x'].isnull()) & (df.index.isin(incl)), df['x'].interpolate(),df['x'])
    

    哪些打印:

          x  outlier_flag
    0  10.0             1
    1   NaN             1
    2  30.0             1
    3  40.0            -1
    4  50.0             1
    

    【讨论】:

      【解决方案2】:

      使用np.where:

      df['x'] =  np.where(df['outlier_flag'] == -1, (df['x'].shift(1) + df['x'].shift(-1))/2, df['x'])
      print(df)
      
            x  outlier_flag
      0  10.0             1
      1   NaN             1
      2  30.0             1
      3  40.0            -1
      4  50.0             1
      

      【讨论】:

      • 谢谢,我赞成你的回答!这将是一种解决方案。但是有没有办法使用.interpolate()?因为,我想使用多项式插值,而不是线性插值。有时df['x'].shift(1) 的值是nan,您的插值方法也会导致nan,位,interpolate() 将能够处理这种情况。有什么想法吗?
      • @NeStack 您可以做的一个选择是创建另一个包含这些 NAN 的数据帧并从当前数据帧中删除 NAN,然后将 X 分配给 NAN,其 -1 表示异常值标志。之后进行插值并最终合并数据帧
      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 2015-09-13
      • 2020-11-30
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2023-02-25
      • 1970-01-01
      相关资源
      最近更新 更多