统计学异常值剔除
虽然移除数据中排名前 N% 的值有助于清除明显离群的点,但它的缺点是即使数据本身无误,也总是按相同比例删除。一个常用的替代方法,是删除距离均值超过 3 个标准差的数据。实现方式是先计算相关列的均值和标准差,从而得到上界和下界,然后将这些界限作为掩码应用到 DataFrame。这样可以确保只移除与整体明显不同的数据;如果数据较为集中,被移除的点也会更少。
本练习是课程的一部分
Python 中的机器学习特征工程
练习说明
- 计算
so_numeric_df的ConvertedSalary列的标准差和均值。 - 分别在均值的两个方向上,按 3 个标准差计算上下界。
- 截取
so_numeric_dfDataFrame,仅保留ConvertedSalary落在lower与upper界限内的所有行。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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()