メンバーシップ制約

Pythonで学ぶデータクリーニング

Adel Nehme

Content Developer @DataCamp

 

 

 

 

 

 

 

第2章 - 文字列とカテゴリデータの問題

Pythonで学ぶデータクリーニング

カテゴリとメンバーシップ制約

あらかじめ定義された有限のカテゴリ集合

データ型 数値表現
婚姻状況 unmarried, married 0,1
世帯収入区分 0-20K, 20-40K, ... 0,1, ..
返済状況 default,payed,no_loan 0,1,2

 

婚姻状況は unmarried _か_ married _のみ_

Pythonで学ぶデータクリーニング

なぜこうした問題が起きるのか?

categorical_issues

Pythonで学ぶデータクリーニング

どう対処するか?

    categories

Pythonで学ぶデータクリーニング

# 調査データを読み込んで表示
study_data = pd.read_csv('study.csv')
study_data
      name   birthday blood_type
1     Beth 2019-10-20         B-
2 Ignatius 2020-07-08         A-
3     Paul 2019-08-12         O+
4    Helen 2019-03-17         O-
5 Jennifer 2019-12-17         Z+
6  Kennedy 2020-04-27         A+
7    Keith 2019-04-19        AB+
# 正しい血液型の一覧
categories
  blood_type
1         O-
2         O+
3         A-
4         A+
5         B+
6         B-
7        AB+
8        AB-
Pythonで学ぶデータクリーニング

# 調査データを読み込んで表示
study_data = pd.read_csv('study.csv')
study_data
      name   birthday blood_type
1     Beth 2019-10-20         B-
2 Ignatius 2020-07-08         A-
3     Paul 2019-08-12         O+
4    Helen 2019-03-17         O-
5 Jennifer 2019-12-17         Z+  <--
6  Kennedy 2020-04-27         A+
7    Keith 2019-04-19        AB+
# 正しい血液型の一覧
categories
  blood_type
1         O-
2         O+
3         A-
4         A+
5         B+
6         B-
7        AB+
8        AB-
Pythonで学ぶデータクリーニング

結合に関する注意

Pythonで学ぶデータクリーニング

血液型での左アンチ結合

Pythonで学ぶデータクリーニング

血液型での内部結合

Pythonで学ぶデータクリーニング

不整合なカテゴリの検出

inconsistent_categories = set(study_data['blood_type']).difference(categories['blood_type'])
print(inconsistent_categories)
{'Z+'}
# 不整合なカテゴリの行を取得して表示
inconsistent_rows = study_data['blood_type'].isin(inconsistent_categories)

study_data[inconsistent_rows]
      name   birthday blood_type
5 Jennifer 2019-12-17         Z+
Pythonで学ぶデータクリーニング

不整合カテゴリの除外

inconsistent_categories = set(study_data['blood_type']).difference(categories['blood_type'])
inconsistent_rows = study_data['blood_type'].isin(inconsistent_categories)
inconsistent_data = study_data[inconsistent_rows]

# 不整合カテゴリを除外し、整合データのみ取得 consistent_data = study_data[~inconsistent_rows]
      name   birthday blood_type
1     Beth 2019-10-20         B-
2 Ignatius 2020-07-08         A-
3     Paul 2019-08-12         O+
4    Helen 2019-03-17         O-
...    ...      ...          ...
Pythonで学ぶデータクリーニング

練習しましょう!

Pythonで学ぶデータクリーニング

Preparing Video For Download...