python - 如何在数据框列中查找系列
问题描述
我有一个系列(str 值),我需要在数据框列中查找是否存在,并为每个具有 1/0 值的 str 值创建一个新列。下面是我的做法,需要帮助编写一个函数来更有效地完成这项任务。谢谢
旅游、啤酒厂、比萨、餐厅、食品、酒店和旅游,
Mydata['Tours'] = Mydata.categories.str.contains('Tours', regex=False)
Mydata['Breweries'] = Mydata.categories.str.contains('Breweries', regex=False)
Mydata['Pizza'] = Mydata.categories.str.contains('Pizza', regex=False)
Mydata['Restaurants'] = Mydata.categories.str.contains('Restaurants', regex=False)
Mydata['Food'] = Mydata.categories.str.contains('Food', regex=False)
Mydata['Hotels & Travel'] = Mydata.categories.str.contains('Hotels & Travel', regex=False)
Mydata['Tours'].apply(lambda x: 1 if x == True else 0)
Mydata['Breweries'].apply(lambda x: 1 if x == True else 0)
Mydata['Pizza'].apply(lambda x: 1 if x == True else 0)
Mydata['Restaurants'].apply(lambda x: 1 if x == True else 0)
Mydata['Food'].apply(lambda x: 1 if x == True else 0)
Mydata['Hotels & Travel'].apply(lambda x: 1 if x == True else 0)
解决方案
看起来你只需要一个for
循环:
tags = ['Tours','Breweries','Pizza','Restaurants','Food','Hotels & Travel']
for tag in tags:
Mydata[tag] = Mydata.categories.str.contains(tag, regex=False)
Mydata[tag].apply(lambda x: 1 if x == True else 0)
BTWlambda x: 1 if x == True else 0
与 几乎相同int
,我相信您可以简单地使用.astype(int)
(未经测试)
推荐阅读
- python - Django mongo db过滤器查询不返回任何数据
- c# - c# timer 如果设置过快
- swift - 在 ARkit2 中跟踪多张图像并播放它们的视频
- wordpress - Wordpress 页面生成器不保存或关闭
- apache-spark - 从 spark 数据框中选择或删除重复的列
- visual-studio - 如何将参数转义到在 VS 构建后事件中运行的 PS 脚本
- angular - 定义受保护和不受保护的重复路由(Angular 5)
- c# - 获取下拉列表中的选定项目以查看 CRUD 模型
- asynchronous - F# 是否有 Async.Sequential 来匹配 Async.Parallel?
- sonarqube - Sonarqube 在 Ubuntu 16.04 上启动,但我无法访问它