如何识别元组的“键”/3项元组的列表?

2024-09-29 19:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于收入价值表,因此:

enter image description here

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

我将提取一个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等),并从每个项目的收入中减去费用。这些词条将从香蕉表、猕猴桃表等中提取,如下所示:

enter image description here

如果品牌名称总是包含收入表中的产品名称,那么为了编制一个适当的收入值集合,以便与香蕉支出dict进行比较,我只提取名称中包含“Banana”的所有品牌,并在Banana expenses dict中匹配关键字,对它们的值执行提取。在

但事实并非如此,因此我需要另一种方式来了解在Revenue dict中,“OtherBrand”是香蕉。(在香蕉dict中,我已经知道它是香蕉,因为它来自香蕉桌)。我可以提取一个列表或元组(tuples of(Product,Brand,Revenue)),现在我们有了由Product列提供的附加信息。但是,由于元组没有键的概念,我如何遍历这个新集合,以期望的方式提取每一元组的收入(即,认识到OtherBrand是香蕉等)


Tags: columnsofkeyin名称forvalue情况
2条回答

您可以将水果作为关键,并对品牌进行分组:

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)

使用输入输出:

^{pr2}$

然后,您可以使用这些键减去费用。

使用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')))

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

然后,对于字典中的每个产品类型,您可以轻松地拉出该产品的品牌列表,如果需要,可以创建一个包含3元组列表的新字典(brand, revenue, expenses)

相关问题 更多 >

    热门问题