您需要在这里使用模糊字符串匹配。对于 python,作为一个选项,您可以查看 thefuzz 包,它为字符串计算 Levenshtein distance。
举个例子:
from thefuzz import fuzz
st = 'DEPART 1'
strs = [ 'Départ 1', 'DEP1','depart 1',' DEPART 1 ']
for s in strs:
l_d= fuzz.ratio(st.lower(), s.lower()) # Levenshtein distance
print(st, s, '|', 'Levenshtein distance: ', l_d, 'is the same: ', l_d > 60)
输出:
DEPART 1 Départ 1 | Levenshtein distance: 88 is the same: True
DEPART 1 DEP1 | Levenshtein distance: 67 is the same: True
DEPART 1 depart 1 | Levenshtein distance: 100 is the same: True
DEPART 1 DEPART 1 | Levenshtein distance: 89 is the same: True
查看更多信息:https://www.datacamp.com/community/tutorials/fuzzy-string-python
使用它你可以实现你的目标。
“替换任何不正确的字符串”:
import pandas as pd
from thefuzz import fuzz
st = 'DEPART 1'
df = pd.DataFrame(columns=['DEPART 1','DEP1','depart 1','depart 1','not even close'])
print(df)
cols = []
for column in df.columns:
if fuzz.ratio(st.lower(), column.lower()) > 60:
cols.append(st)
else:
cols.append(column)
df.columns = cols
print(df)
输出:
Columns: [DEPART 1, DEP1, depart 1, depart 1, not even close]
Columns: [DEPART 1, DEPART 1, DEPART 1, DEPART 1, not even close]
“检查列名的出现”:
import pandas as pd
import collections
df = pd.DataFrame(columns=['DEPART 1','DEP1','depart 1','depart 1','not even close'])
print(collections.Counter(df.columns))
输出:
Counter({'depart 1': 2, 'DEPART 1': 1, 'DEP1': 1, 'not even close': 1})