Last active
August 17, 2021 05:23
-
-
Save andresmascl/d87c4a8ca9d0ad7f81fd5f5a3d3b9d42 to your computer and use it in GitHub Desktop.
Take a string and a pandas series. Return which element in the series is the string most similar to, and the percentage of similarity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from difflib import SequenceMatcher | |
def similitud(a, serie): | |
""" | |
Calculates greatest similarity between a string (a) and a pandas series containing strings | |
:return: number between 0 and 1 indicating similarity percentage, and element from the | |
pandas series it is most similar to | |
""" | |
df_resultados = pd.DataFrame(columns=serie, index=['similitud']) | |
A = str(a).strip() | |
A = ''.join(filter(lambda x: x in printable, A)) | |
for col in df_resultados.columns: | |
b = str(col).strip() | |
b = ''.join(filter(lambda x: x in printable, b)) | |
df_resultados.at['similitud', col] = SequenceMatcher(None, A.upper(), b.upper()).ratio() | |
df_resultados = df_resultados.astype('float32') | |
col_max = df_resultados.idxmax(axis=1)[0] | |
similitud_max = df_resultados.max(axis=1)[0] | |
return similitud_max, col_max |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've found myself using this snippet often when standardizing fields imputed by humans, for instance in survey tables.