【问题标题】:Python - [Pandas / Lists / Numpy?] Select recipes randomly to create menu with nutrient rangePython - [Pandas / Lists / Numpy?] 随机选择食谱以创建具有营养范围的菜单
【发布时间】:2020-05-26 05:48:15
【问题描述】:

我尝试为自己创建一个简单的脚本,其中我有一个包含我自己食谱的数据库并生成一周的日菜单。这是一个示例数据库:

recipe_data = {'Recipe': ['Macaroni', 'Mashed_potato', 'Risotto', 'Sandwich', 'Tuna_salad', 'Pancakes', 'Overnight_oats'],
        'Recipe_type': ['Dinner', 'Dinner', 'Dinner',  'Lunch', 'Lunch', 'Breakfast', 'Breakfast'],
        'Protein': [50, 40, 30, 20, 20, 10, 10],
        'Carbohydrates': [100, 80, 60, 50, 40, 30, 20]}

df = pd.DataFrame(recipe_data)

           Recipe Recipe_type  Protein  Carbohydrates
0        Macaroni      Dinner       50            100
1   Mashed_potato      Dinner       40             80
2         Risotto      Dinner       30             60
3        Sandwich       Lunch       20             40
4      Tuna_salad       Lunch       20             40
5        Pancakes   Breakfast       10             20
6  Overnight_oats   Breakfast       10             20

我想创建一个函数,我可以说:生成一个随机菜单 [早餐、午餐和晚餐组合],蛋白质组合总和在 65 - 85 之间,碳水化合物组合总和在:135 - 165 之间。在这个例子中会生成一个类似的选项:

           Recipe Recipe_type  Protein  Carbohydrates
0        Macaroni      Dinner       50            100
3        Sandwich       Lunch       20             40
5        Pancakes   Breakfast       10             20

我对 python 很陌生,我看到了一些看起来像我的问题但找不到解决方法的答案。因此,非常欢迎任何帮助。到目前为止,我只得到了这个:

print(df.groupby(['Recipe_type'])['Protein'].apply(np.random.choice).reset_index())
  Recipe_type  Protein
0   Breakfast       10
1      Dinner       30
2       Lunch       20

(所以显然这并没有打印所有列,也没有考虑任何营养总和..)

很可能我实际上应该使用列表或字典,所以这些建议也可以帮助我很多:)

【问题讨论】:

    标签: python pandas list numpy random


    【解决方案1】:

    一种方法是交叉合并和过滤:

    df['dummy'] =1
    
    (df[df.Recipe_type=='Breakfast']                     # all breakfast recipes
        .merge(df[df.Recipe_type=='Lunch'], on='dummy')  # cross merge with lunch
        .merge(df[df.Recipe_type=='Dinner'], on='dummy') # cross merge with dinner
        .assign(Total_Protein=lambda x: x.filter(like='Protein').sum(1))  # calculate total protein
        .assign(Total_Carbonhydrates=lambda x:x.filter(like='Carbohydrates').sum(1)) # calculate total carbonhydrates
        .query('65<=Total_Protein<=85 & 135<=Total_Carbonhydrates<=165')  # filter with given criteria
    )
    

    您会得到一个数据框,其中Recipe_x, Recipe_y, Recipe 代表所需总数为ProteinCarbonhydrates 的膳食。

    【讨论】:

    • 非常感谢您的回答!但是我应该如何解释“假人”?它返回并返回 {error: KeyError: 'dummy'},所以我想我应该用其他东西替换它(要加入的列或索引级别名称),但我不确定如何..
    猜你喜欢
    • 2020-10-22
    • 2015-09-15
    • 2018-10-31
    • 2015-07-09
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多