如何识别 3 项元组的 tuple/list 中的 "keys"?

How to identify "keys" of a tuple/list of 3-item tuples?

鉴于 table 的收入值因此:

要注意的一个关键点(也是我问题的核心)是品牌名称 几乎 总是,但并非总是,包含相应的产品名称。在最后一个 Banana 条目的情况下,它没有。

我将提取 品牌 <-> 收入 对的 dict 对,首先计算那些具有多个条目的品牌,并在这些情况下求和,使用描述的方法 。所以:

revenuePerBrandDict = {}
brandRevenueTuples = []
i=0
for brand in ourTab.columns[1][1:-1]: # ignore first (zeroth) and last row
    brandRevenueTuples.append((campaign.value, round(ourTab.columns[3][i].value,2)))
    i+=1
for key, value in brandRevenueTuples:
        revenuePerBrandDict[key] = revenuePerBrandDict.get(key, 0) + value

然后我会将这个字典中的键和值交叉引用到(香蕉字典费用,猕猴桃字典费用[=45中的每个字典=] 等),并从收入中减去费用,逐项减去。这些字典将从香蕉 table、猕猴桃 table 等中提取,如下所示:

如果品牌名称总是在收入中包含产品名称table,那么为了编制适当的收入值集合以与 Banana 费用进行比较dict,例如,我将只提取所有名称包含 'Banana' 的品牌,并且为了匹配 Banana expenses dict 中的键,对它们的值执行提取。

但事实并非如此,所以 我需要另一种方法来知道在 Revenue 指令中,'OtherBrand' 是香蕉。(在 Banana dict,我已经知道它是Banana了,因为它来自Bananatable)。我可以提取(产品、品牌、收入)的列表或元组,而不是提取 dict 的品牌<->收入对,现在我们有了 [=34] 提供的附加信息=]产品列。但是由于元组没有键的概念,我如何遍历这个新集合,以所需的方式提取每个元组的收入(即认识到 OtherBrand 是一个香蕉等)

在我看来,您想按产品类型对第一个 table 中的数据进行分组。我建议使用一个字典,其中键是产品类型,值是元组列表 [(brand, revenue),(..., ...)].

然后,对于字典中的每个产品类型,您可以轻松地提取该产品的品牌列表,并在需要时制作一个包含三元组列表的新字典 (brand, revenue, expenses)

您可以使用水果作为关键字并对品牌进行分组:

from collections import defaultdict
import csv

with open("in.csv") as f:
    r = csv.reader(f)
    next(r) # skip header
    # fruite will be keys, values will be dicts
    # with brands as keys  and running totals for rev as values
    d = defaultdict(lambda: defaultdict(int))
    for fruit, brand, rev in r:
        d[fruit][brand] += float(rev)

使用你的输入输出:

from pprint import pprint as pp

pp(dict(d))
{'Apple': defaultdict(<type 'int'>, {'CrunchApple': 1.7}),
 'Banana': defaultdict(<type 'int'>, {'BananaBrand': 4.0,   'OtherBrand': 3.2}),
 'Kiwi': defaultdict(<type 'int'>, {'NZKiwi': 1.2}),
 'Pear': defaultdict(<type 'int'>, {'PearShaped': 6.2})

然后您可以使用按键减去费用。

使用pandas生活更容易你可以分组和求和:

import pandas as pd

df = pd.read_csv("in.csv")

print(df.groupby(("A","B")).sum())

输出:

A      B               
Apple  CrunchApple  1.7
Banana BananaBrand  4.0
       OtherBrand   3.2
Kiwi   NZKiwi       1.2
Pear   PearShaped   6.2

或按水果和品牌获取分组:

groups = df.groupby(["A","B"])

print(groups.get_group(('Banana', 'OtherBrand')))

print(groups.get_group(('Banana', 'BananaBrand')))