簡體   English   中英

如何將列表值與不完全相等的數據框列進行比較?

[英]How do I compare list values to a dataframe column that are not exactly equal?

我是Python的新手,正在嘗試使用Pandas清理csv。

我當前的數據框如下所示:

   Time   Summary
0  10     ABC Company
1  4      Company XYZ
2  20     The Awesome Company
3  4      Record B

我有一個看起來像這樣的列表:

clients = ['ABC', 'XYZ', 'Awesome']

我面臨的挑戰是從數據框中提取等於列表中任何值的值。

我希望我的數據框看起來像這樣:

   Time   Summary              Client
0  10     ABC Company          ABC
1  4      Company XYZ          XYZ
2  20     The Awesome Company  Awesome
3  4      Record B             NaN

我已經研究了正則表達式,.any和in,但是我似乎無法在for循環中獲得正確的語法。

您可以執行以下操作:

import numpy as np


def match_client(summary):
    client_matches = [client for client in ['ABC', 'XYZ', 'Awesome'] if client in summary]
    if len(client_matches) == 0:
        return np.nan
    else:
        return ', '.join(client_matches)

df['Client'] = df['Summary'].map(match_client)

只是為了補充@Simon的答案,如果要將其應用於其他客戶,也可以將客戶列表作為參數傳遞。

import numpy as np

def match_client(summary, clients):
    client_matches = [client for client in clients if client in summary]
    if len(client_matches) == 0:
        return np.nan
    else:
        return ', '.join(client_matches)

clients = ['ABC', 'XYZ', 'Awesome']
df['Client'] = df['Summary'].map(lambda x: match_client(x, clients))

您只需要使用lambda函數,即可將clients作為map內部的額外參數傳遞。

pandas.Series.str.extract

假設只有一場比賽

df.assign(Client=df.Summary.str.extract(f"({'|'.join(clients)})"))

   Time              Summary   Client
0    10          ABC Company      ABC
1     4          Company XYZ      XYZ
2    20  The Awesome Company  Awesome
3     4             Record B      NaN

pandas.Series.str.findall

可能還有更多……您永遠不會知道。

df.join(df.Summary.str.findall('|'.join(clients)).str.join('|').str.get_dummies())

   Time              Summary  ABC  Awesome  XYZ
0    10          ABC Company    1        0    0
1     4          Company XYZ    0        0    1
2    20  The Awesome Company    0        1    0
3     4             Record B    0        0    0

暫無
暫無

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

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