在處理數據用於建模的時候,遇到了長尾數據,需要處理異常值,於是參考網上的資料,重新寫了函數。
是把一個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)