欠損値への対処

Pythonで学ぶ探索的データ分析

George Boorman

Curriculum Manager, DataCamp

なぜ欠損データは問題か

  • 分布に影響
    • 背の高い学生の身長が欠損
  • 母集団の代表性低下
    • 例:最年長層のデータ不足で偏り
  • 誤った結論の原因

サンプルと母集団の身長分布。サンプルは最大値と平均が低い

Pythonで学ぶ探索的データ分析

データ職の求人データ

説明 データ型
Working_Year 取得年 Float
Designation 役職 String
Experience 経験レベル(例: "Mid", "Senior" String
Employment_Status 雇用形態(例: "FT", "PT" String
Employee_Location 勤務国 String
Company_Size 企業規模ラベル(例: "S", "M", "L" String
Remote_Working_Ratio リモート勤務割合(%) Integer
Salary_USD 給与(米ドル) Float
Pythonで学ぶ探索的データ分析

経験別の給与

クリーンなデータでの経験別給与の箱ひげ図。上限は約60万ドル

欠損を含むデータでの経験別給与の箱ひげ図。上限は約45万ドル

Pythonで学ぶ探索的データ分析

欠損の確認

print(salaries.isna().sum())
Working_Year            12
Designation             27
Experience              33
Employment_Status       31
Employee_Location       28
Company_Size            40
Remote_Working_Ratio    24
Salary_USD              60
dtype: int64
Pythonで学ぶ探索的データ分析

欠損値への対処戦略

  • 欠損を削除
    • 全体の5%以下
  • 平均・中央値・最頻値で補完
    • 分布と文脈に依存
  • サブグループ別に補完
    • 経験レベルで中央値給与が異なる
Pythonで学ぶ探索的データ分析

欠損値の削除

threshold = len(salaries) * 0.05
print(threshold)
30
Pythonで学ぶ探索的データ分析

欠損値の削除

cols_to_drop = salaries.columns[salaries.isna().sum() <= threshold]

print(cols_to_drop)
Index(['Working_Year', 'Designation', 'Employee_Location',
       'Remote_Working_Ratio'],
      dtype='object')
salaries.dropna(subset=cols_to_drop, inplace=True)
Pythonで学ぶ探索的データ分析

要約統計量での補完

cols_with_missing_values = salaries.columns[salaries.isna().sum() > 0]
print(cols_with_missing_values)
Index(['Experience', 'Employment_Status', 'Company_Size', 'Salary_USD'], 
    dtype='object')
for col in cols_with_missing_values[:-1]:
    salaries[col].fillna(salaries[col].mode()[0])
Pythonで学ぶ探索的データ分析

残りの欠損の確認

print(salaries.isna().sum())
Working_Year             0
Designation              0
Experience               0
Employment_Status        0
Employee_Location        0
Company_Size             0
Remote_Working_Ratio     0
Salary_USD              41
Pythonで学ぶ探索的データ分析

サブグループ別補完

salaries_dict = salaries.groupby("Experience")["Salary_USD"].median().to_dict()

print(salaries_dict)
{'Entry': 55380.0, 'Executive': 135439.0, 'Mid': 74173.5, 'Senior': 128903.0}
Pythonで学ぶ探索的データ分析

サブグループ別補完

salaries["Salary_USD"] = salaries["Salary_USD"].fillna(salaries["Experience"].map(salaries_dict))
Pythonで学ぶ探索的データ分析

欠損は解消!

print(salaries.isna().sum())
Working_Year            0
Designation             0
Experience              0
Employment_Status       0
Employee_Location       0
Company_Size            0
Remote_Working_Ratio    0
Salary_USD              0
dtype: int64
Pythonで学ぶ探索的データ分析

Passons à la pratique !

Pythonで学ぶ探索的データ分析

Preparing Video For Download...