簡體   English   中英

如何替換 DataFrame (Python) 中的字符串列表中的字符串?

[英]How to replace a string in a list of strings in a DataFrame (Python)?

我有一個數據框,它由兩個單獨列中的列表列表組成。

import pandas as pd
data = pd.DataFrame()
data["Website"] = [["google.com", "amazon.com"], ["google.com"], ["aol.com", "no website"]]
data["App"] = [["Ok Google", "Alexa"], ["Ok Google"], ["AOL App", "Generic Device"]]

這就是數據框的樣子

我需要用第二列中的相應字符串(此處:“通用設備”)替換第一列(此處:“無網站”)中的某些字符串。 替換字符串在列表中與需要替換的字符串具有相同的索引。

到目前為止什么不起作用:我為列表和數據幀嘗試了幾種形式的str.replace(x,y) ,但沒有任何效果。 簡單的replace(x,y)不起作用,因為我需要替換幾個不同的字符串。 我想我無法理解索引的事情。 我已經用谷歌搜索和計算了兩個小時,但還沒有找到解決方案。

提前謝謝了! 對不起,英語不好或菜鳥錯誤,我還在學習。

-最大限度

試試這個,你可以在數組中定義可替換的值並執行。

def f(x,items):
    for rep in items:
        if rep in list(x.Website):
            x.Website[list(x.Website).index(rep)]=list(x.App)[list(x.Website).index(rep)]    
    return x

items = ["no website"]
data = data.apply(lambda x: f(x,items),axis=1)

輸出:

                     Website                        App
0   [google.com, amazon.com]         [Ok Google, Alexa]
1               [google.com]                [Ok Google]
2  [aol.com, Generic Device]  [AOL App, Generic Device]

定義替換函數並使用 apply 進行矢量化

def replacements(websites, apps):
    " Substitute items in list replace_items that's found in websites "
    replace_items = ["no website", ] # can add to this list of keys 
                                     # that trigger replacement

    for i, k in enumerate(websites):
        # Check each item in website for replacement
        if k in replace_items:
            # This is an item to be replaced
            websites[i] = apps[i]  # replace with corresponding item in apps

    return websites

# Create Dataframe
websites = [["google.com", "amazon.com"], ["google.com"], ["aol.com", "no website"]]
app = [["Ok Google", "Alexa"], ["Ok Google"], ["AOL App", "Generic Device"]]
data = list(zip(websites, app))
df = pd.DataFrame(data, columns = ['Websites', 'App'])

# Perform replacement
df['Websites'] = df.apply(lambda row: replacements(row['Websites'], row['App']), axis=1)
print(df)

輸出

                   Websites                        App
0   [google.com, amazon.com]         [Ok Google, Alexa]
1               [google.com]                [Ok Google]
2  [aol.com, Generic Device]  [AOL App, Generic Device]

首先祝大家節日快樂!

我不確定您的預期輸出是什么,我不確定您之前嘗試過什么,但我認為這可能有效:

data["Website"] = data["Website"].replace("no website", "Generic Device")

我真的希望這會有所幫助!

您可以創建這樣的函數:

def f(replaced_value, col1, col2):
    def r(s):
        while replaced_value in s[col1]:
            s[col1][s[col1].index(replaced_value)] = s[col2][s[col1].index(replaced_value)]
        return s
    return r

並使用apply

df=df.apply(f("no website","Website","App"), axis=1)
print(df)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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