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

2024-04-05

我想替换我的数据框中的单词

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 行的数据框。

提前致谢!


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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas 用字典中的值替换部分字符串 的相关文章

随机推荐