计算缺失占比
自动化是数据科学的未来。学会将部分数据准备工作自动化,长期收益可观。在本练习中,您将自动化处理:当某列的缺失数据超过指定阈值时,将其删除。
本练习是课程的一部分
使用 PySpark 进行特征工程
练习说明
- 定义函数
column_dropper(),其参数为数据框df和介于 0 到 1 之间的浮点数threshold。 - 使用
where()、isNull()和count()计算该列缺失值所占的百分比。 - 判断缺失占比是否高于阈值;若是,使用
drop()删除该列。 - 在
df上运行column_dropper(),将阈值设为 .6
交互式实操练习
通过完成这段示例代码来试试这个练习。
def column_dropper(df, threshold):
# Takes a dataframe and threshold for missing values. Returns a dataframe.
total_records = df.____()
for col in df.columns:
# Calculate the percentage of missing values
missing = df.____(df[col].____()).____()
missing_percent = ____ / ____
# Drop column if percent of missing is more than threshold
if ____ > ____:
df = df.____(col)
return df
# Drop columns that are more than 60% missing
df = ____(____, ____)