Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas replace part of string with values from dictionary

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!

like image 849
Amas Avatar asked May 14 '19 08:05

Amas


1 Answers

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
like image 175
Rakesh Avatar answered Oct 11 '22 12:10

Rakesh