Python Pandas:检查一列中的字符串是否包含在同一行中另一列的字符串中 [英] Python Pandas: Check if string in one column is contained in string of another column in the same row
本文介绍了Python Pandas:检查一列中的字符串是否包含在同一行中另一列的字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数据框:
I have a dataframe like this:
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.
And want to create another column, C, out of A and B such that for the same row, if the string in column A is contained in the string of column B, then C = True and if not then C = False.
我正在寻找的示例输出是这样的:
The example output I am looking for is this:
RecID| A |B |C
--------------------
1 |a | abc |True
2 |b | cba |True
3 |c | bca |True
4 |d | bac |False
5 |e | abc |False
有没有一种方法可以在不使用循环的情况下在 Pandas 中快速执行此操作?谢谢
Is there a way to do this in pandas quickly and without using a loop? Thanks
推荐答案
你需要apply
with 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:
Another solution with list comprehension
is faster, but there has to be no 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
这篇关于Python Pandas:检查一列中的字符串是否包含在同一行中另一列的字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文