python - 遍历熊猫数据框/系列的特定列
问题描述
我正在实施一篇研究论文,其中我必须根据其成分对美食进行分类。提供配料训练数据集和测试数据集。一切正常。模型已根据 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)
。如何改进搜索用户输入的成分是否有效。
解决方案
我认为这回答了您的问题,如果输入不在列成分中,它将无效,您可能必须更改 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)
推荐阅读
- python - 使用 Python 将 datetime64 转换为整数小时
- assembly - 为什么 Visual Studio 编译器使用“mov esp,ebp”/“pop ebp”而不是“leave”?
- sql - 使用列表中的元素设置 SQL WHERE 值
- python - 用于 2D ALE 图的 Python PyALE 函数的值错误
- api - 如何仅通过 API 调用在 Rasa 中成功训练和替换模型?
- c# - ReturnType 控件 Xamarin
- python - 正则表达式从 div 中删除所有内容
- java - 参数索引超出范围(2个参数,即1)
- java - 如何将 3D 模型添加到 medeiapipe 项目?
- powershell - 为什么我不能粘贴我在 Windows cmd 上复制的所有内容