比较字符串

Python 数据清洗

Adel Nehme

VP of AI Curriculum, DataCamp

本章内容

 

 

 

 

 

 

第4章 - 记录链接

Python 数据清洗

最小编辑距离

将一个字符串变为另一个所需的最少步骤数

Python 数据清洗

最小编辑距离

将一个字符串变为另一个所需的最少步骤数

Python 数据清洗

最小编辑距离

Python 数据清洗

最小编辑距离

当前最小编辑距离:2

Python 数据清洗

最小编辑距离

最小编辑距离:5

Python 数据清洗

最小编辑距离

 

Python 数据清洗

最小编辑距离算法

算法 操作
Damerau-Levenshtein 插入、替换、删除、换位
Levenshtein 插入、替换、删除
Hamming 仅替换
Jaro distance 仅换位
... ...

 

可用包: nltk, thefuzz, textdistance ..

Python 数据清洗

最小编辑距离算法

算法 操作
Damerau-Levenshtein 插入、替换、删除、换位
Levenshtein _插入_、_替换_、_删除_
Hamming 仅替换
Jaro distance 仅换位
... ...

 

可用包: thefuzz

Python 数据清洗

简单的字符串比较

# Lets us compare between two strings
from thefuzz import fuzz

# Compare reeding vs reading fuzz.WRatio('Reeding', 'Reading')
86
Python 数据清洗

部分字符串与不同顺序

# Partial string comparison
fuzz.WRatio('Houston Rockets', 'Rockets')
90
# Partial string comparison with different order
fuzz.WRatio('Houston Rockets vs Los Angeles Lakers', 'Lakers vs Rockets')
86
Python 数据清洗

与数组比较

# Import process
from thefuzz import process

# Define string and array of possible matches
string = "Houston Rockets vs Los Angeles Lakers"
choices = pd.Series(['Rockets vs Lakers', 'Lakers vs Rockets', 
                     'Houson vs Los Angeles', 'Heat vs Bulls'])

process.extract(string, choices, limit = 2)
[('Rockets vs Lakers', 86, 0), ('Lakers vs Rockets', 86, 1)]
Python 数据清洗

用字符串相似度合并类别

第2章

使用 .replace()"eur" 统一为 "Europe"

 

如果变体太多怎么办?

"EU", "eur", "Europ", "Europa", "Erope", "Evropa"...

 

                                                                                                字符串相似度!

Python 数据清洗

用字符串匹配合并类别

print(survey['state'].unique())
id          state
0      California
1            Cali
2      Calefornia
3      Calefornie
4      Californie
5       Calfornia
6      Calefernia
7        New York
8   New York City
...
categories
  state
0 California
1 New York
Python 数据清洗

合并所有州名

# For each correct category
for state in categories['state']:

# Find potential matches in states with typoes matches = process.extract(state, survey['state'], limit = survey.shape[0])
# For each potential match match for potential_match in matches: # If high similarity score if potential_match[1] >= 80:
# Replace typo with correct category survey.loc[survey['state'] == potential_match[0], 'state'] = state
Python 数据清洗

记录链接

记录链接

Python 数据清洗

Vamos praticar!

Python 数据清洗

Preparing Video For Download...