我想替换数据框中的字词
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句