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

时间:2019-05-14 08:15:43

标签: python pandas 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()]))

我想知道是否有任何方法可以做到这一点?我有一个约有15,000行的数据框。

谢谢!

3 个答案:

答案 0 :(得分:1)

.replaceregex=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

答案 1 :(得分:0)

您可以对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

答案 2 :(得分:0)

您可以将public class Gate_Class { public Gate_Class(int tag, Rectangle rectangle) { //... Rectangle = rectangle; } public Rectangle Rectangle { get; } } 访问器的replace方法与从str的键生成的正则表达式一起使用:

dic

输出:

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