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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To calculate the Levenshtein distance between two strings in a pandas DataFrame, you can use the python-Levenshtein package, which provides a function called distance to compute the Levenshtein distance. First, ensure that you have the python-Levenshtein package installed:
code
pip install python-Levenshtein
Once you have the package installed, you can apply the distance function to each row in your DataFrame. Here's an example of how you can do this:
python
import pandas as pd
from Levenshtein import distance
# Sample DataFrame
df = pd.DataFrame({
'col1': ['kitten', 'sitting'],
'col2': ['sitting', 'fitted']
})
# Compute Levenshtein distance and store in new column
df['levenshtein_distance'] = df.apply(lambda row: distance(row['col1'], row['col2']), axis=1)
print(df)
This will create a new column in your DataFrame called levenshtein_distance, which contains the Levenshtein distances between the strings in col1 and col2 for each row.
If you encounter any issues with the python-Levenshtein package or if it is not available for your platform, you can alternatively use the FuzzyWuzzy package, which also includes a method for calculating the Levenshtein distance. It can be installed with:
code
pip install fuzzywuzzy
Here's how you would use FuzzyWuzzy to accomplish the same task:
python
import pandas as pd
from fuzzywuzzy import fuzz
# Sample DataFrame
df = pd.DataFrame({
'col1': ['kitten', 'sitting'],
'col2': ['sitting', 'fitted']
})
# Compute Levenshtein distance and store in new column
df['levenshtein_distance'] = df.apply(lambda row: fuzz.ratio(row['col1'], row['col2']), axis=1)
print(df)
Note that fuzz.ratio returns a similarity score from 0 to 100, not the actual Levenshtein distance. If you specifically need the Levenshtein edit distance, you'll need to use python-Levenshtein or another library that directly computes it.