首页 > 解决方案 > 按用户计算图书库存

问题描述

有一张表,其中包含2014年的数据。结构如下:每个用户可以发行不同数量的书籍类别。

User-id|Book-Category
1      |Thrill        
2      |Thrill       
3      |Mystery       
3      |Mystery       

要求是为每个用户查找所发行的每种类型的图书类别。这些数据已经存在于 csv 文件中,但它是按年提供的。我必须添加所有这些值。例如:

data for 2014
u-id|book|count
1   |b1  |2  
1   |b2  |4
...  ...  ...

data for 2015
u-id|book|count
1   |b1  |21
2   |b3  |12  
//like the above format,available till 2018.(user1 with book b1 should have a count of 23

现在,我编写了一个 python 脚本,在其中我只是制作了一个字典并迭代每一行,如果存在键(u-id+book-category),则添加数值,否则在该字典中插入键值对,为该脚本中的每年明智的文件执行此操作,因为某些文件的大小> 1.5GB,脚本继续运行 7/8 小时,不得不停止它。

代码:

    import requests
    import csv
    import pandas as pd

    Dict = {}

    with open('data_2012.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            if row['a']+row['b'] not in Dict:
                Dict[row['a']+row['b']] = row['c']
##like this,iterating over the year wise files and finally writing the data to a different file.'a' and 'b' are mentioned at the first line of the data files for an easy access.

有什么方法可以让我们在 python 中更优雅地实现此功能或编写 Map-Reduce 作业?

标签: pythonpandascsvhadoop

解决方案


推荐阅读