I have a pandas dataframe with two string columns, col1 and col2. I’d like to create a…
- User
I have a pandas dataframe with two string columns, col1 and col2. I’d like to create a third column containing the Levenshtein distance between col1 and col2. How do I do it?
- Assistant
You can use the
python-Levenshteinpackage to compute Levenshtein distance, which is not included in the standard library, so you'll need to install it first:pip install python-LevenshteinThen to create a third column with Levenshtein distance, you can apply the
Levenshtein.distancefunction to each row of your DataFrame. Here is a simple example:import pandas as pd import Levenshtein as lv # Assuming df is your DataFrame and it has columns 'col1' and 'col2' df = pd.DataFrame({ 'col1': ['kitten', 'sitting', 'flights', 'stubborn'], 'col2': ['sitting', 'kitten', 'lights', 'lubber'] }) df['levenshtein'] = df.apply(lambda row: lv.distance(row.col1, row.col2), axis=1) print(df)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.