開始使用免費開始

計算遺漏比例

自動化是資料科學的未來。學會把部分資料前處理自動化,長期會很有幫助。在這個練習中,你將自動化處理:當欄位的遺漏資料超過特定門檻時就將其刪除。

本練習屬於課程

使用 PySpark 進行特徵工程

檢視課程

練習說明

  • 定義函式 column_dropper(),參數為 df(DataFrame)與 threshold(介於 0 到 1 的浮點數)。
  • 使用 where()isNull()count() 計算遺漏值所佔的百分比。
  • 檢查遺漏百分比是否高於門檻;若是,使用 drop() 刪除該欄位。
  • df 上執行 column_dropper(),並將門檻設定為 0.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 = ____(____, ____)
編輯並執行程式碼