计数字符串特征

2024-04-20 10:43:50 发布

您现在位置:Python中文网/ 问答频道 /正文

数据位于csv的数据帧中。我是这样带进来的:

listing = pd.read_csv("listings.csv")

我有一个来自AirBnB数据集的便利设施栏。我很感兴趣的是,AirBnB什么时候将“允许宠物”作为其便利设施的一部分

in:   listing['amenities'].head(2)

out:  0     {TV,"Cable TV",Internet,Wifi,"Paid parking off...
      1     {TV,"Cable TV",Internet,Wifi,Kitchen,"Free par...

在便利设施专栏中,我们经常会看到{TV,"Cable TV",Internet,Wifi,"Pets Allowed"...}

我如何计算“允许宠物”的行数

我试过:

pets_count = listing['amenities'].str.contains('pet*').sum()
pets_count

返回59,但我知道这不是值,因为还有更多


Tags: csv数据宠物readcounttvinternetwifi
1条回答
网友
1楼 · 发布于 2024-04-20 10:43:50

一个简单的解决方案是用,分割字符串并删除"

像这样:

s =  """{TV,"Cable TV",Internet,Wifi,Kitchen}"""
amenities = [amenitie.replace('"','').strip() for amenitie in s.replace('{', '').replace('}', '').split(',')]
if 'Pets allowed' in amenities:
  print('pets allowed !')

相关问题 更多 >