鉴于收入价值表,因此:
需要注意的一个关键点(也是我问题的核心)是,品牌名称几乎总是包含相应的产品名称,但并不总是包含相应的产品名称。在最后一个香蕉入口的情况下,它没有
我将提取一个dict
的品牌<;->;收入对,首先说明那些有多个条目的品牌,并在这些情况下使用here方法进行总结。所以:
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
然后,我将把这个dict中的键和值交叉引用到每个dict(香蕉dict of bananaexpenses,kiwi dictexpenses等),并从每个项目的收入中减去费用。这些词条将从香蕉表、猕猴桃表等中提取,如下所示:
如果品牌名称总是包含收入表中的产品名称,那么为了编制一个适当的收入值集合,以便与香蕉支出dict进行比较,我只提取名称中包含“Banana”的所有品牌,并在Banana expenses dict中匹配关键字,对它们的值执行提取。在
但事实并非如此,因此我需要另一种方式来了解在Revenue dict中,“OtherBrand”是香蕉。(在香蕉dict中,我已经知道它是香蕉,因为它来自香蕉桌)。我可以提取一个列表或元组(tuples of(Product,Brand,Revenue)),现在我们有了由Product列提供的附加信息。但是,由于元组没有键的概念,我如何遍历这个新集合,以期望的方式提取每一元组的收入(即,认识到OtherBrand是香蕉等)
您可以将水果作为关键,并对品牌进行分组:
使用输入输出:
^{pr2}$然后,您可以使用这些键减去费用。
使用pandas生活更容易你可以分组和求和:
输出:
或按水果和品牌分组:
在我看来,您想将第一个表中的数据按产品类型分组。我建议使用一个字典,其中键是产品类型,值是元组列表
[(brand, revenue),(..., ...)]
。然后,对于字典中的每个产品类型,您可以轻松地拉出该产品的品牌列表,如果需要,可以创建一个包含3元组列表的新字典
(brand, revenue, expenses)
。相关问题 更多 >
编程相关推荐