[英]Merge two dataframe if one string column is contained in another column in Pandas
[英]Python Pandas: Check if string in one column is contained in string of another column in the same row
我有一個這樣的數據框:
RecID| A |B
----------------
1 |a | abc
2 |b | cba
3 |c | bca
4 |d | bac
5 |e | abc
並且想要從 A 和 B 中創建另一列 C,這樣對於同一行,如果 A 列中的字符串包含在 B 列的字符串中,則 C = True,否則 C = False。
我正在尋找的示例輸出是這樣的:
RecID| A |B |C
--------------------
1 |a | abc |True
2 |b | cba |True
3 |c | bca |True
4 |d | bac |False
5 |e | abc |False
有沒有辦法在不使用循環的情況下快速地在熊貓中做到這一點? 謝謝
你需要apply
in
:
df['C'] = df.apply(lambda x: x.A in x.B, axis=1)
print (df)
RecID A B C
0 1 a abc True
1 2 b cba True
2 3 c bca True
3 4 d bac False
4 5 e abc False
list comprehension
另一個解決方案更快,但必須沒有NaN
s:
df['C'] = [x[0] in x[1] for x in zip(df['A'], df['B'])]
print (df)
RecID A B C
0 1 a abc True
1 2 b cba True
2 3 c bca True
3 4 d bac False
4 5 e abc False
我無法得到@jezreal 提供的任何一個答案來處理第一列中的 None 。 對列表理解稍加改動就可以處理它:
[x[0] in x[1] if x[0] is not None else False for x in zip(df['A'], df['B'])]
如果您將字符串與字符串進行比較並獲得類型錯誤,您可以這樣編碼:
df['C'] = df.apply(lambda x: str(x.A) in str(x.B), axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.