簡體   English   中英

Pandas - 檢查另一個數據框列中的系列值

[英]Pandas - check for series value in another dataframe column

我正在嘗試檢查一個數據框列中的字符串值是否包含在另一個數據框列中。 我的數據框是:

d = {'col1': ['Live', 'Live','Live','Deferrred'], 'col2': ['Live', 'Not live,Deferred', 'Deferred,Live','Not live']}
df = pd.DataFrame(data=d)
print(df)
        col1               col2
0       Live               Live
1       Live  Not live,Deferred
2       Live      Deferred,Live
3  Deferrred           Not live 

如果 Col1 中的值是 Col2 中的分隔值之一,則新列 'Check' 應顯示 True:

        col1               col2 Check
0       Live               Live     Y
1       Live  Not live,Deferred     N
2       Live      Deferred,Live     Y
3  Deferrred           Not live     N

我試過了:

conditions = [df['col1'].isin(df['col2'])]
choices = [('Y')]
df['Check'] = np.select(conditions, choices, default = 'N')

然而,這對於Live in Not live返回True而它應該返回False

我也試過:

conditions = [df['col2'].contains(df['col1'])]

然而這返回: AttributeError: 'Series' object has no attribute 'contains'

有沒有辦法讓.isin()區分大小寫,或者有沒有另一種方法讓Live in Not live return False

這是您可以執行的一種方法:

df['Check'] = (df
              .apply(lambda x: 'Y' if x['col1'] in x['col2'] else 'N', 1))

使用numpy

import numpy as np

df['Check']=np.bitwise_and( df['col2'].str.split(",").map(set), df['col1'].str.split().map(set) ).ne(set())

輸出:

        col1               col2  Check
0       Live               Live   True
1       Live  Not live,Deferred  False
2       Live      Deferred,Live   True
3  Deferrred           Not live  False

暫無
暫無

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

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