gpt4 book ai didi

python - 根据某些列条件从 Pandas 数据框中获取所有行组合?

转载 作者:行者123 更新时间:2023-11-28 18:56:33 26 4
gpt4 key购买 nike

我有一个 Pandas Dataframe,它按以下格式在每一行存储一个食物 -

Id   Calories   Protein   IsBreakfast   IsLunch   IsDinner
1 300 6 0 1 0
2 400 12 1 1 0
.
.
.
100 700 25 0 1 1

我想打印具有以下条件的所有三行组合 -

  1. 组合应至少包含早餐、午餐和晚餐中的一种。
  2. 卡路里总和应在一定范围内(例如 minCal < 三行卡路里总和 < maxCal)
  3. 蛋白质也有类似的情况。

现在,我首先遍历所有早餐项目,选择午餐项目。然后遍历所有晚餐项目。选择组合后,我添加相关列并检查值是否在所需范围内

最佳答案

您可以使用 this answer 中描述的方法生成一个新的 DataFrame,其中包含原始数据中三行的所有组合:

from itertools import combinations
import pandas as pd

# Using skbrhmn's df
df = pd.DataFrame({"Calories": [100, 200, 300, 400, 500],
"Protein": [10, 20, 30, 40, 50],
"IsBreakfast": [1, 1, 0, 0, 0],
"IsLunch": [1, 0, 0, 0, 1],
"IsDinner": [1, 1, 1, 0, 1]})

comb_rows = list(combinations(df.index, 3))
comb_rows

输出:

[(0, 1, 2),
(0, 1, 3),
(0, 1, 4),
(0, 2, 3),
(0, 2, 4),
(0, 3, 4),
(1, 2, 3),
(1, 2, 4),
(1, 3, 4),
(2, 3, 4)]

然后创建一个新的 DataFrame,其中包含原始框架中所有数字字段的总和,包括三行的所有可能组合:

combinations = pd.DataFrame([df.loc[c,:].sum() for c in comb_rows], index=comb_rows)

print(combinations)

Calories Protein IsBreakfast IsLunch IsDinner
(0, 1, 2) 600 60 2 1 3
(0, 1, 3) 700 70 2 1 2
(0, 1, 4) 800 80 2 2 3
(0, 2, 3) 800 80 1 1 2
(0, 2, 4) 900 90 1 2 3
(0, 3, 4) 1000 100 1 2 2
(1, 2, 3) 900 90 1 0 2
(1, 2, 4) 1000 100 1 1 3
(1, 3, 4) 1100 110 1 1 2
(2, 3, 4) 1200 120 0 1 2

最后您可以应用您需要的任何过滤器:

filtered = combinations[
(combinations.IsBreakfast>0) &
(combinations.IsLunch>0) &
(combinations.IsDinner>0) &
(combinations.Calories>600) &
(combinations.Calories<1000) &
(combinations.Protein>=80) &
(combinations.Protein<120)
]
print(filtered)

Calories Protein IsBreakfast IsLunch IsDinner
(0, 1, 4) 800 80 2 2 3
(0, 2, 3) 800 80 1 1 2
(0, 2, 4) 900 90 1 2 3

关于python - 根据某些列条件从 Pandas 数据框中获取所有行组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57678251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com