我有一个像这样的数据框:
id k1 k2 same
1 re_setup oo_setup true
2 oo_setup oo_setup true
3 alerting bounce false
4 bounce re_oversetup false
5 re_oversetup alerting false
6 alerting_s re_setup false
7 re_oversetup oo_setup true
8 alerting bounce false
因此,我需要对包含或不包含字符串“ setup”的行进行分类。
And simple output would be:
id k1 k2 same
1 re_setup oo_setup true
2 oo_setup oo_setup true
3 alerting bounce false
4 bounce re_setup false
5 re_setup alerting false
6 alerting_s re_setup false
7 re_setup oo_setup true
8 alerting bounce false
我已经尝试过这样做,但是据我所知,选择多个列时出现错误。
data['same'] = data[data['k1', 'k2'].str.contains('setup')==True]
我认为您需要apply
使用str.contains
,因为它仅适用于Series
(一列):
print (data[['k1', 'k2']].apply(lambda x: x.str.contains('setup')))
k1 k2
0 True True
1 True True
2 False False
3 False True
4 True False
5 False True
6 True True
7 False False
然后添加DataFrame.all
检查True
每行是否所有
data['same'] = data[['k1', 'k2']].apply(lambda x: x.str.contains('setup')).all(1)
print (data)
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_setup False
4 5 re_setup alerting False
5 6 alerting_s re_setup False
6 7 re_setup oo_setup True
7 8 alerting bounce False
或每行DataFrame.any
至少检查一次True
:
data['same'] = data[['k1', 'k2']].applymap(lambda x: 'setup' in x).any(1)
print (data)
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_setup True
4 5 re_setup alerting True
5 6 alerting_s re_setup True
6 7 re_setup oo_setup True
7 8 alerting bounce False
applymap
明智检查的另一种解决方案:
data['same'] = data[['k1', 'k2']].applymap(lambda x: 'setup' in x).all(1)
print (data)
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_setup False
4 5 re_setup alerting False
5 6 alerting_s re_setup False
6 7 re_setup oo_setup True
7 8 alerting bounce False
如果只有2列,则带有&
likeall
或|
like的简单链条条件any
:
data['same'] = data['k1'].str.contains('setup') & data['k2'].str.contains('setup')
print (data)
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_setup False
4 5 re_setup alerting False
5 6 alerting_s re_setup False
6 7 re_setup oo_setup True
7 8 alerting bounce False
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句