【问题标题】:Count by pairs/Pivot table按对计数/数据透视表
【发布时间】:2017-12-14 14:19:59
【问题描述】:

我有以下 CSV 格式的数据:

Date    Name    Color
12/11   Thomas  Blue
12/31   Andy    Black
12/21   Luise   Red
12/41   Mark    Blue
12/11   Ronda   Black
12/11   Thomas  Blue
12/21   Mark    Green
12/11   Ronda   Black
12/31   Luise   Red
12/41   Luise   Green

我想创建一个基于对的计数,如下所示的数据透视表。理想情况下也是 CSV 文件

        Blue    Black   Red Green
Thomas   2          
Andy             1      
Luise                    2    1
Mark     1                    1
Ronda            1            1

我不完全确定如何解决这个问题。也不能使用熊猫。 :(

【问题讨论】:

    标签: python python-3.x csv


    【解决方案1】:

    您可以使用defaultdictdefaultdictint 来存储颜色计数。

    import csv, collections
    
    counts = collections.defaultdict(lambda: collections.defaultdict(int))
    colors = set()
    with open("data.csv") as f:
        reader = csv.reader(f, delimiter="\t")
        next(reader) # skip first line
        for date, name, color in reader:
            counts[name][color] += 1
            colors.add(color)
    

    然后,打印不同颜色的计数(或写入 CSV):

    colors = list(colors)
    print(colors)
    for name in counts:
        print(name + "\t" + "\t".join(str(counts[name][color]) for color in colors))
    

    结果(我将把微调留给你):

    ['Red', 'Blue', 'Green', 'Black']
    Ronda   0   0   0   2
    Thomas  0   2   0   0
    Andy    0   0   0   1
    Luise   2   0   1   0
    Mark    0   1   1   0
    

    【讨论】:

    • 谢谢,工作正常!我必须研究代码才能理解它(因为我是菜鸟),但它做到了!
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多