用Pandas中行之前和之后的平均值替换给定列的异常值 [英] Replace given columns' outliers with mean of before and after rows' values in Pandas
本文介绍了用Pandas中行之前和之后的平均值替换给定列的异常值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用前后值替换以下数据框中score
列中的异常值?
How can I replace outliers in score
column from the following dataframe with the before and after values?
date score
0 2018-07 51.964556
1 2018-08 63.497871
2 2018-09 85.304209
3 2018-10 8.590178 ---> outlier
4 2018-11 54.376001
5 2018-12 65.844745
6 2019-01 53.050123
7 2019-02 39.915868
8 2019-04 3.051802 ---> outlier
9 2019-05 57.487205
10 2019-06 95.101470
11 2019-07 79.879340
12 2019-08 77.007162
13 2019-09 54.567136
14 2019-10 63.899944
预期输出为:
date score
0 2018-07 51.964556
1 2018-08 63.497871
2 2018-09 85.304209
3 2018-10 69.840105
4 2018-11 54.376001
5 2018-12 65.844745
6 2019-01 53.050123
7 2019-02 39.915868
8 2019-04 48.701537
9 2019-05 57.487205
10 2019-06 95.101470
11 2019-07 79.879340
12 2019-08 77.007162
13 2019-09 54.567136
14 2019-10 63.899944
非常感谢.
推荐答案
使用zscore
的解决方案,仅将常用的3
值更改为1.5
:
Solution with zscore
, only changed common used 3
value to 1.5
:
from scipy import stats
mask = (np.abs(stats.zscore(df['score'])) > 1.5)
df.score = df.score.mask(mask).interpolate()
print (df)
date score
0 2018-07 51.964556
1 2018-08 63.497871
2 2018-09 85.304209
3 2018-10 69.840105
4 2018-11 54.376001
5 2018-12 65.844745
6 2019-01 53.050123
7 2019-02 39.915868
8 2019-04 48.701537
9 2019-05 57.487205
10 2019-06 68.683273
11 2019-07 79.879340
12 2019-08 77.007162
13 2019-09 54.567136
14 2019-10 63.899944
这篇关于用Pandas中行之前和之后的平均值替换给定列的异常值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文