簡體   English   中英

python pandas - 檢查列中的部分字符串是否存在於其他列中

[英]python pandas - Check if partial string in column exists in other column

取一個樣本數據集:

df = pd.DataFrame([['Mexico', 'Chile'], ['Nicaragua', 'Nica'], ['Colombia', 'Mex']], columns = ["col1", "col2"])

dataframe 看起來像這樣:

我有兩列。 我想檢查第二列中的值是否存在於第一列中。 這包括檢查部分字符串。

所需的 output 是:

在此處輸入圖像描述

我能夠比較第二列中每一行的整個值,但這不考慮部分字符串:

df['compare'] = np.where(df['col2'].isin(df['col1']), 'yes', 'no')

我還能夠檢查列中是否存在單個值,該值檢查部分字符串但不包括“col2”列中的每一行。

df['compare'] = df['col1'].str.contains('Mex')

我怎樣才能同時做這兩個?

這看起來像一個昂貴的操作。 你可以試試:

df['col2'].apply(lambda x: 'Yes' if df['col1'].str.contains(x).any() else 'No')

Output:

0     No
1    Yes
2    Yes
Name: col2, dtype: object

暫無
暫無

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

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