7

I would like to replace the words in my dataframe

df = pd.DataFrame({"Text": ["The quick brown fox jumps over the lazy dog"]})

which match the keys in the following dictionary

dic = {"quick brown fox": "fox",
       "lazy dog": "dog}

with their values.

The expected outcome is

    Text
0   The fox jumps over the dog

I tried the following code but there is no change to my df.

df["Text"] = df["Text"].apply(lambda x: ' '.join([dic.get(i, i) for x in x.split()]))

I would like to know if there is any way to do this? I have a dataframe with around 15k rows.

Thanks in advance!

3 Answers 3

9

Use .replace with regex=True

Ex:

import pandas as pd

dic = {"quick brown fox": "fox", "lazy dog": "dog", "u": "you"}
#Update as per comment
dic = {r"\b{}\b".format(k): v for k, v in dic.items()}

df = pd.DataFrame({"Text": ["The quick brown fox jumps over the lazy dog"]})
df["Text"] = df["Text"].replace(dic, regex=True)
print(df)

Output:

                         Text
0  The fox jumps over the dog
Sign up to request clarification or add additional context in comments.

2 Comments

As my dictionary is used to replace contraction and acronyms, it is quite comprehensive. I have a key value pair which is {"u": "you"}. This causes the output to change to "The fox jyoumps over the dog". Do you know of any way to get around this?
@Amas use dic = {r"\b{}\b".format(k): v for k, v in dic.items()}. Updated snippet
2

You could use a for loop with Series.str.replace:

for pat, repl in dic.items():
    df.Text = df.Text.str.replace(pat, repl)

[out]

                         Text
0  The fox jumps over the dog

Comments

2

You can use the replace method of the str accessor along with a regex generated from the keys of dic:

df['Text'].str.replace('|'.join(dic), lambda string: dic[string.group()])

Output:

0    The fox jumps over the dog
Name: Text, dtype: object

1 Comment

Finally, some working solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.