Python 数据清洗
Adel Nehme
Content Developer @DataCamp
预定义的有限类别集
| 数据类型 | 示例值 | 数值表示 |
|---|---|---|
| 婚姻状况 | unmarried, married |
0,1 |
| 家庭收入分组 | 0-20K, 20-40K, ... |
0,1, .. |
| 贷款状态 | default,payed,no_loan |
0,1,2 |
婚姻状况只能是 unmarried _或_ married


# 读取研究数据并打印
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-
# 读取研究数据并打印
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-



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+
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 数据清洗