【发布时间】:2021-01-17 15:26:17
【问题描述】:
我想遍历数据框的每一行,如果列和列表中的字符串匹配,我会在新列中添加一个元素。 在此示例中,我想添加一个新列来对产品进行分类。因此,如果该列的一行与列表中的一个匹配,则类别可以是“饮料”或“食品”,如果不匹配,则类别将是其他。
list_drinks={'Water','Juice','Tea'}
list_food={'Apple','Orange'}
data = {'Price': ['1', '5','3'], 'Product': ['Juice','book', Pen]}
for (i,j) in itertools.zip_longest(list_drinks,list_food):
for index in data.index:
if(j in data.loc[index,'product']):
data["Category"] = "Food"
elif(i in data.loc[index,'product']):
data["Category"] ="drinks"
else:
data["Category"]="Other"
输出将是:
Price Product Category
1 Juice drinks
5 book Other
3 Pen Other
我的问题主要是我不知道如何匹配列表和行之间的模式。我也试过:
str.contains 但它不起作用。
【问题讨论】:
标签: python pandas dataframe loops for-loop