[英]Pandas replace part of string with values from dictionary
我想替换数据框中的字词
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行的数据框。
提前致谢!
将.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
您可以在Series.str.replace
使用for
循环:
for pat, repl in dic.items():
df.Text = df.Text.str.replace(pat, repl)
[出]
Text
0 The fox jumps over the dog
您可以将str
访问器的replace
方法与从dic
的键生成的regex一起使用:
df['Text'].str.replace('|'.join(dic), lambda string: dic[string.group()])
输出:
0 The fox jumps over the dog
Name: Text, dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.