简体   繁体   English

熊猫用字典中的值替换字符串的一部分

[英]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没有变化。

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. 我有一个约15k行的数据框。

Thanks in advance! 提前致谢!

Use .replace with regex=True .replaceregex=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 : 您可以在Series.str.replace使用for循环:

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 : 您可以将str访问器的replace方法与从dic的键生成的regex一起使用:

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

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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