Python Pandas:检查一列中的字符串是否包含在同一行的另一列中 [英] Python Pandas: Check if string in one column is contained in string of another column in the same row

查看:411
本文介绍了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

有没有一种方法可以在熊猫中快速且不使用循环的方式进行此操作?谢谢

Is there a way to do this in pandas quickly and without using a loop? Thanks

推荐答案

您需要applyin:

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 NaNs:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆