欠損データへの対処

Pythonによる探索的データ分析

George Boorman

Curriculum Manager, DataCamp

欠損データはなぜ問題なのか?

  • 分布に影響を与える
    • 背の高い生徒の身長データが欠損
  • 母集団を適切に代表していない
    • 特定のグループが母集団に対して不均衡に含まれている(例:最年長の生徒のデータが不足)
  • 誤った結論につながる

Sample versus population height distribution, showing the sample has a lower maximum and mean

Pythonによる探索的データ分析

データ専門職の職務データ

列 説明 データ型
Working_Year データを取得した年 浮動小数点数
Designation 職種 文字列
Experience 経験レベル(例: "Mid", "Senior") 文字列
Employment_Status 雇用契約の種類(例:"FT"、"PT") 文字列
Employee_Location 雇用先の国 文字列
Company_Size 企業規模を表すラベル(例:"S"、"M"、"L") 文字列
Remote_Working_Ratio 勤務時間のうちリモートで働く割合 整数
Salary_USD 給与(米ドル) 浮動小数点数
Pythonによる探索的データ分析

経験レベル別の給与

Box plot of salaries by experience level using the clean dataset, with an upper limit near 600000 dollars

Box plot of salaries by experience level using a dataset with missing values, showing an upper limit near 450000 dollars

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による探索的データ分析

お疲れさまでした!

Pythonによる探索的データ分析

Preparing Video For Download...