为了账号安全,请及时绑定邮箱和手机立即绑定

如何重新分类熊猫数据框列?

如何重新分类熊猫数据框列?

皈依舞 2021-06-16 17:54:37
我有一个 Pandas 数据框,看起来像这样:> print(df)           image_name                       tags0                img1       class1 class2 class31                img2                     class22                img3              class2 class33                img4                     class1如何重新分类tags列,以便为任何具有class3值的行分配字符串“yes”,其他所有字符串都分配字符串“no”?我知道我可以使用以下方法检查搜索词的实例:df['tags'].str.contains('class3')但是,我不确定如何将其集成到手头的任务中。以下是预期的输出:           image_name                       tags0                img1                        yes1                img2                         no2                img3                        yes3                img4                         no
查看完整描述

3 回答

?
www说

TA贡献1775条经验 获得超8个赞

使用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


查看完整回答
反对 回复 2021-06-29
?
守着一只汪

TA贡献1872条经验 获得超3个赞

你也可以这样做:


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


查看完整回答
反对 回复 2021-06-29
?
UYOU

TA贡献1878条经验 获得超4个赞

也许这会比 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


查看完整回答
反对 回复 2021-06-29
  • 3 回答
  • 0 关注
  • 199 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号