python 异常值处理-替换为值

在处理数据用于建模的时候,遇到了长尾数据,需要处理异常值,于是参考网上的资料,重新写了函数。

是把一个DataFrame的某列超过预计范围(IQR方法)的数据重新赋值为上、下限的方法,如果要删除异常值,需要修改后面几个。

 1 import pandas as pd
 2 
 3 def outliners(data,col,scale=3):
 4     def box_plot_outliners(data_ser,box_scale):
 5         IQR=box_scale*(data_ser.quantile(0.75)-data_ser.quantile(0.25))
 6         val_low=data_ser.quantile(0.25)-IQR
 7         val_up=data_ser.quantile(0.75)+IQR
 8         rule_low=(data_ser<val_low)
 9         rule_up=(data_ser>val_up)
10         return rule_low,rule_up,val_low,val_up
11     data_n=data.copy()
12     data_series=data_n[col]
13     rule_low,rule_up,val_low,val_up=box_plot_outliners(data_series,box_scale=scale)
14     data_n[col].loc[rule_up]=val_up
15     data_n[col].loc[rule_low]=val_low
16     return data_n

使用的时候,直接把一个df输入,指定一个列,就可以输出一个新的df

  df_new=outliners(df,'the_col_name',scale=3)

posted @ 2020-11-18 10:31  Shilo  阅读(3272)  评论(0编辑  收藏  举报