[英]How to check if a string value of one row is contained in the string value of another row in the same column in pandas dataframe
[英]Pandas: check if string value in one column is part of string of another column in same row of dataframe - current script returning all Yes
我有以下 dataframe:
df = pd.DataFrame([['50030', '36 @ 3159 W/270, LWD[GR,RES,PWD] @ 4015', '3159'],
['50030', '36 @ 3159 W/270, LWD[GR,RES,PWD] @ 4015', '3994'],
['50030', '36 @ 3159 W/270, LWD[GR,RES,PWD] @ 4015', '5401'],
['50030', '26 @ 3994, LWD[GR,RES,PWD] @ 5430, 20 @ 5401', '3159'],
['50030', '26 @ 3994, LWD[GR,RES,PWD] @ 5430, 20 @ 5401', '3994'],
['50030', '26 @ 3994, LWD[GR,RES,PWD] @ 5430, 20 @ 5401', '5401']],
columns = ["WKEY", "Description", "DEPTH"])
我想將 DEPTH 列中的值(這是一個字符串值)與 Description 列中的字符串僅針對同一行進行比較。 一個名為“比較”的新列將有一個是或否,這取決於它是否存在。
基於這篇文章: python pandas - 檢查列中的部分字符串是否存在於其他列中,我嘗試了以下代碼:
df['Compare'] = df['DEPTH'].apply(lambda x: 'Yes' if df['Description'].str.contains(x).any() else 'No')
但是,它返回是的所有行:
應該是,不,不,不,不,是,是。
最終計划是刪除所有在 DEPTH 列中沒有值的行,這些行也列在同一行的 Description 列中的某處。
我覺得我離讓它發揮作用只有一步之遙,所以任何方向都會受到贊賞。
謝謝!
在你的情況下
df['Compare'] = df.apply(lambda x: 'Yes' if x['DEPTH'] in x['Description'] else 'No',axis=1)
df
Out[133]:
WKEY Description DEPTH Compare
0 50030 36 @ 3159 W/270, LWD[GR,RES,PWD] @ 4015 3159 Yes
1 50030 36 @ 3159 W/270, LWD[GR,RES,PWD] @ 4015 3994 No
2 50030 36 @ 3159 W/270, LWD[GR,RES,PWD] @ 4015 5401 No
3 50030 26 @ 3994, LWD[GR,RES,PWD] @ 5430, 20 @ 5401 3159 No
4 50030 26 @ 3994, LWD[GR,RES,PWD] @ 5430, 20 @ 5401 3994 Yes
5 50030 26 @ 3994, LWD[GR,RES,PWD] @ 5430, 20 @ 5401 5401 Yes
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.