【问题标题】:Pandas - How to replace those exception values with NaNPandas - 如何用 NaN 替换这些异常值
【发布时间】:2021-04-13 00:29:51
【问题描述】:

有一个DataFrame是这样的:

           cost
0   8762.000000
1   -1
2   7276.000000
3   9574.000000
4   -1
..          ...
59  5508.000000
60  7193.750000
61  5927.333333
62  -1
63  4972.000000

-1是这种情况下的异常值,那么如何将-1替换为NaN。然后如何插入 NaN 进行替换。

之后清理了DataFrame。但是DataFrame可能有一些异常的高低值,然后如何插入异常高低值进行替换。

【问题讨论】:

    标签: python pandas data-science


    【解决方案1】:

    要替换-1 以插入值,请使用NaNs 替换Series.interpolate

    df['cost'] = df['cost'].replace(-1, np.nan).interpolate()
    

    如果还需要删除异常值(异常高值和低值),您可以通过Series.quantileSeries.between 识别它们并将它们替换为Series.where 中的NaNs(首先替换-1):

    print (df)
                 cost
    0     8762.000000
    1       -1.000000
    2     7276.000000
    3   957400.000000
    4       -1.000000
    59    5508.000000
    60    7193.750000
    61      59.333333
    62      -1.000000
    63    4972.000000
    
    df['cost'] = df['cost'].replace(-1, np.nan)
    
    q_low = df["cost"].quantile(0.01)
    q_hi  = df["cost"].quantile(0.99)
    
    m = df["cost"].between(q_low, q_hi, inclusive=False)
    
    df['cost'] = df['cost'].where(m).interpolate()
    print (df)
               cost
    0   8762.000000
    1   8019.000000
    2   7276.000000
    3   6686.666667
    4   6097.333333
    59  5508.000000
    60  7193.750000
    61  6453.166667
    62  5712.583333
    63  4972.000000
    

    【讨论】:

      猜你喜欢
      • 2021-06-22
      • 2022-10-05
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 2019-09-12
      • 1970-01-01
      • 2021-03-02
      相关资源
      最近更新 更多