对于以下数据df
:
id k1 k2
0 1 re_setup oo_setup
1 2 oo_setup oo_setup
2 3 alerting bounce
3 4 bounce re_oversetup
4 5 re_oversetup alerting
5 6 alerting_s re_setup
6 7 re_oversetup oo_setup
7 8 alerting bounce
8 9 alerting_bounce bounce
我们希望:如果K1
和K2
列包含字符setup
或bounce
,则返回True
。否则,返回False
。请注意,如果K1
包含setup
,K2
包含bounce
,或者 * 反之亦然 *,则这种情况下返回False
。
如何实现呢?谢谢。
预期成果如下:
id k1 k2 same
0 1 re_setup oo_setup True
1 2 oo_setup oo_setup True
2 3 alerting bounce False
3 4 bounce re_oversetup False
4 5 re_oversetup alerting_bounce False
5 6 alerting_s re_setup False
6 7 re_oversetup oo_setup True
7 8 alerting bounce False
8 9 alerting_bounce bounce True
我尝试使用df['same1'] = df[['k1', 'k2']].apply(lambda x: x.str.contains('setup|bounce')).all(1)
,它返回以下结果:
id k1 k2 same same1
0 1 re_setup oo_setup True True
1 2 oo_setup oo_setup True True
2 3 alerting bounce False False
3 4 bounce re_oversetup False True incorrect result
4 5 re_oversetup alerting_bounce False True incorrect result
5 6 alerting_s re_setup False False
6 7 re_oversetup oo_setup True True
7 8 alerting bounce False False
8 9 alerting_bounce bounce True True
我们可以看到第3行和第4行返回了错误的结果。
- 参考:**
If one row in two columns contain the same string python pandas
2条答案
按热度按时间iswrvxsc1#
使用
str.extract
并比较结果:输出:
所有匹配项
输出:
ruarlubt2#
您可以使用、更改列名和字符串: