简体   繁体   中英

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM