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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With