python - 如何识别元组/3项元组列表的 "keys"?

标签 python python-2.7 dictionary key tuples

给定收入值表:

enter image description here

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

我将提取品牌<->收入对的字典,首先考虑那些具有多个条目的品牌,并在这些情况下使用所描述的方法进行求和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

然后,我将将此字典中的键和值交叉引用到每个字典(香蕉费用的字典,猕猴桃费用的字典等),并减去收入中的支出,逐项计算。这些字典将从香蕉表、猕猴桃表等中提取,如下所示:

enter image description here

如果品牌名称​​始终包含收入表中的产品名称,那么为了编译适当的收入值集合以与香蕉费用字典进行比较,例如,我只需提取所有名称中包含“Banana”的品牌,为了匹配 Banana 费用字典中的键,请对其值进行提取。

但事实并非如此,所以我需要另一种方式来知道在 Revenue 字典中,“OtherBrand”是一个 Banana。(在 Banana 字典中,我已经知道它是香蕉,因为它来自香蕉 table )。我可以提取((产品、品牌、收入)的元组)的列表或元组,而不是提取品牌 <-> 收入对的 dict,现在我们有了由产品列。但由于元组没有键的概念,我如何迭代这个新集合,以所需的方式提取每个元组的收入(即认识到 OtherBrand 是香蕉等。 )

最佳答案

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

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

关于python - 如何识别元组/3项元组列表的 "keys"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31214051/

相关文章:

python - 如何从机器人向用户发送 DM 并通过 Discord.py 捕获响应

引号中的python 2.7循环索引

python - 如何返回 while 循环的产品

haskell - 在 Haskell 中使用映射时跳过异常

python - 如何返回与字典中最小值对应的键列表

python - opencv2 Aruco 库模块不适用于 python

python - 在 Python 2 或 Python 3 上导入 Openpyxl

python - 如何在一个表达式中合并两个字典(合并字典)?

list - 如何使用 List.map 在 int list 列表上应用函数?

python - 在 Numpy 数组中查找模式