首页 > 解决方案 > 遍历熊猫数据框/系列的特定列

问题描述

我正在实施一篇研究论文,其中我必须根据其成分对美食进行分类。提供配料训练数据集和测试数据集。一切正常。模型已根据 SGD、RandomForest 和 Naive Bayes 的准确性使用最佳方法进行训练。我正在使用随机森林,因为它的准确性优于 NB 和 SGD。测试数据集经过测试,预测工作绝对正常。现在我想通过手动输入(使用input()python)成分来预测美食。当我尝试在此处命名的熊猫系列/数据框中搜索时,问题就来了Y = train_data['all_ingredients'] OR Y = train_data['ingredients']


def check_ing(ing):
    if ing in train_data['all_ingredients'].values:
        return True
    return False


no_of_ingredients = input("Total Number Of Ingredients: ")
no_of_ingredients = int(no_of_ingredients)
ingredient = []
for i in range(no_of_ingredients):
    ing = input("Enter Ingredient " + str(i) + " : ")
    if check_ing(ing) is True:
        ingredient.append(ing)

print(ingredient)

问题出在函数的 if 语句中check_ing(ing)。如何改进搜索用户输入的成分是否有效。

结果Y.head()是: 在此处输入图像描述

标签: pythonpandascountvectorizer

解决方案


我认为这回答了您的问题,如果输入不在列成分中,它将无效,您可能必须更改 if 的第一部分

编辑:没有测试它,这应该工作。编辑2:搞砸了复制和粘贴。

all_ing = [item for sublist in train_data["Ingredients"] for item in sublist]

def check_ing(ing):
    if ing in all_ing:
            return True
    else:
        print("invalid ingredient")
        return False 

no_of_ingredients = input("Total Number Of Ingredients: ")
no_of_ingredients = int(no_of_ingredients)
ingredient = []

for i in range(no_of_ingredients):
    ing = input("Enter Ingredient " + str(i) + " : ")
    tf = check_ing(ing)
    if tf is True:
        ingredient.append(ing)

print(ingredient)

推荐阅读