首页 > 解决方案 > 如何在数据框列中查找系列

问题描述

我有一个系列(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)

标签: pythonfunctiondataframe

解决方案


看起来你只需要一个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)(未经测试)


推荐阅读