成员关系约束

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

按血型做左反连接(left anti join)

Python 数据清洗

按血型做内连接(inner join)

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...