【发布时间】:2017-09-15 02:39:40
【问题描述】:
我是一名新的 Python 开发人员,想知道是否有人可以帮助我解决这个问题。我有一个数据集,其中有一列描述公司类型。我注意到该列列出了例如手术、手术。它列出了眼镜、眼镜和验光。因此,我不想在本专栏中有一个庞大的列表,我只想简单地说明如果你找到一个包含“eye”、“glasses”或“opto”的词,那么只需将其更改为“eyewear”。我的初始代码如下所示:
def map_company(row):
company = row['SIC_Desc']
if company in 'Surgical':
return 'Surgical'
elif company in ['Eye', 'glasses', 'opthal', 'spectacles', 'optometers']:
return 'Eyewear'
elif company in ['Cotton', 'Bandages', 'gauze', 'tape']:
return 'First Aid'
elif company in ['Dental', 'Denture']:
return 'Dental'
elif company in ['Wheelchairs', 'Walkers', 'braces', 'crutches', 'ortho']:
return 'Mobility equipments'
else:
return 'Other'
df['SIC_Desc'] = df.apply(map_company,axis=1)
这是不正确的,因为它将每个项目都更改为“其他”,所以很明显我的语法是错误的。有人可以帮我简化我试图重新标记的这个列吗? 谢谢
【问题讨论】:
-
已经验证了进入
company的值? -
为什么不直接使用调试器呢?调试器是你的朋友,抓住机会学习使用调试器!
-
你也可以发布你正在使用的数据集吗?
-
听起来你的病情倒退了。你想要
'Dental' in company。您可以使用any()来获得比较多个值的预期效果,例如:elif any(i in company for i in ['Dental', 'Denture']): ... -
你好 Champion 你能扩展你的代码吗?它似乎不起作用。这就是我所拥有的: def map_company(row): company = row['SIC_Desc'] if any(i in company for i in ['Surgical', 'Surgery']): return 'Surgical' elif any(i in company for i in ['Eye', 'glasses', 'opthal', 'spectacles', 'optometers']): return 'Eyewear' elif any(i in company for i in ['Cotton', 'Bandages', 'gauze'] ', 'tape']): return 'First Aid' else: return 'Other' df['SIC_Desc'] = df.apply(map_company,axis=1)
标签: python