成員限制

用 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 進行資料清理

範例

# Read study data and print it
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+
# Correct possible blood types
categories
  blood_type
1         O-
2         O+
3         A-
4         A+
5         B+
6         B-
7        AB+
8        AB-
用 Python 進行資料清理

範例

# Read study data and print it
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+
# Correct possible blood types
categories
  blood_type
1         O-
2         O+
3         A-
4         A+
5         B+
6         B-
7        AB+
8        AB-
用 Python 進行資料清理

關於連接的備註

用 Python 進行資料清理

在血型上做 left anti join

用 Python 進行資料清理

在血型上做 inner join

用 Python 進行資料清理

找出不一致的類別

inconsistent_categories = set(study_data['blood_type']).difference(categories['blood_type'])
print(inconsistent_categories)
{'Z+'}
# Get and print rows with inconsistent categories
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]

# Drop inconsistent categories and get consistent data only 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...