簡體   English   中英

熊貓用字典中的值替換字符串的一部分

[英]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行的數據框。

提前致謝!

.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

您可以在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM