Pandas用字典的值替换字符串的一部分

7
我想要在我的数据帧中替换单词。
df = pd.DataFrame({"Text": ["The quick brown fox jumps over the lazy dog"]})

与以下字典中的键相匹配

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

带有它们的值。

预期的结果是

    Text
0   The fox jumps over the dog

我尝试了以下代码,但是我的df没有任何变化。
df["Text"] = df["Text"].apply(lambda x: ' '.join([dic.get(i, i) for x in x.split()]))

我想知道是否有办法做到这一点?我有一个大约有15k行的数据框架。
提前感谢!
3个回答

9

使用.replace时,需要添加参数regex=True

示例:

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)

输出:

                         Text
0  The fox jumps over the dog

由于我的字典用于替换缩写和首字母缩略词,因此它非常全面。我有一个键值对,即{"u": "you"}。这会导致输出变为"The fox jyoumps over the dog"。你知道有什么方法可以解决这个问题吗? - Amas
1
@Amas 使用 dic = {r"\b{}\b".format(k): v for k, v in dic.items()}。更新后的代码片段。 - Rakesh

2
你可以使用一个 for 循环和 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

2
你可以使用str访问器的replace方法,结合从dic键生成的正则表达式:
df['Text'].str.replace('|'.join(dic), lambda string: dic[string.group()])

输出:

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

终于,有可行的解决方案了! - bakunet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接