開始使用免費開始

統計式離群值移除

雖然移除資料中前 N% 的極端值有助於排除非常可疑的點,但缺點是即使資料本身正確,也總是會刪掉相同比例的觀測值。常見的替代做法是移除距離平均數超過 3 個標準差的資料。你可以先計算相關欄位的平均數與標準差,以找出上下界,接著將這些界限作為遮罩套用到 DataFrame。這種方法能確保只移除與整體明顯不同的資料;如果資料彼此相當接近,被移除的點也會更少。

本練習屬於課程

Feature Engineering for Machine Learning in Python

檢視課程

練習說明

  • 計算 so_numeric_dfConvertedSalary 欄位之標準差與平均數。
  • 分別在平均數的兩側計算相距 3 個標準差的上下界。
  • 修剪 so_numeric_df DataFrame,只保留 ConvertedSalary 介於 lowerupper 界限之間的所有列。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Find the mean and standard dev
std = so_numeric_df['ConvertedSalary'].____
mean = so_numeric_df['ConvertedSalary'].____

# Calculate the cutoff
cut_off = std * 3
lower, upper = mean - cut_off, ____

# Trim the outliers
trimmed_df = so_numeric_df[(so_numeric_df['ConvertedSalary'] < ____) \ 
                           & (so_numeric_df['ConvertedSalary'] > ____)]

# The trimmed box plot
trimmed_df[['ConvertedSalary']].boxplot()
plt.show()
編輯並執行程式碼