Skip to content

Instantly share code, notes, and snippets.

@andresmascl
Last active August 17, 2021 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andresmascl/d87c4a8ca9d0ad7f81fd5f5a3d3b9d42 to your computer and use it in GitHub Desktop.
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
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
@andresmascl
Copy link
Author

I've found myself using this snippet often when standardizing fields imputed by humans, for instance in survey tables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment