Pandas - 如何用 NaN 替换那些异常值

Pandas - How to replace those exception values with NaN

有一个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是cleaned.But可能DataFrame有一些异常的高低值,然后如何插值异常的高低值进行替换。

要替换 -1 以插入值,请将 NaNs 替换为 Series.interpolate:

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

如果还需要删除离群值(异常的高值和低值),您可以通过 Series.quantile and Series.between and replace them to NaNs in Series.where(首先替换 -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