我有一个看起来像这样的Pandas数据框:
<form>
如何重新分类> print(df)
image_name tags
0 img1 class1 class2 class3
1 img2 class2
2 img3 class2 class3
3 img4 class1
列,以便为任何具有tags
值的行分配字符串“ yes”和其他所有字符串“ no”?
我知道我可以使用以下方法检查搜索字词的实例:
class3
但是,我不确定如何将其集成到手头的任务中。
以下是预期的输出:
df['tags'].str.contains('class3')
答案 0 :(得分:4)
将np.where
用作:
df['tags'] = np.where(df['tags'].str.contains('class3'),'yes','no')
或
df['tags'] = 'no'
df.loc[df['tags'].str.contains('class3'),'tags'] = 'yes'
或
df['tags'] = ['yes' if 'class3' in s else 'no' for s in df3.tags.values]
上述方法的输出:
print(df)
image_name tags
0 img1 yes
1 img2 no
2 img3 yes
3 img4 no
答案 1 :(得分:2)
您也可以这样做:
df['tags'] = df.tags.str.contains('class3').map({True:'Yes',False:'No'})
>>> df
image_name tags
0 img1 Yes
1 img2 No
2 img3 Yes
3 img4 No
答案 2 :(得分:2)
也许这会比str.contains
v=np.array(['Yes','No'])[np.array(['class3' in x for x in df.tags]).astype(int)]
v
Out[267]: array(['No', 'Yes', 'No', 'Yes'], dtype='<U3')
#df['tags']=v
下面的定时列表
#df=pd.concat([df]*1000)
#sacul
%timeit df.tags.str.contains('class3').map({True:'Yes',False:'No'})
The slowest run took 10.12 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.11 ms per loop
#Mine
%timeit np.array(['Yes','No'])[np.array(['class3' in x for x in df.tags]).astype(int)]
1000 loops, best of 3: 390 µs per loop
#Borealis
%timeit np.where(df['tags'].str.contains('class3'),'yes','no')
100 loops, best of 3: 2.46 ms per loop