python - 按用户计算图书库存
问题描述
有一张表,其中包含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 作业?
解决方案
推荐阅读
- python - 如何在mac上的vscode上安装包?
- excel - 如何从其名称或其中的文本中找到列字母?
- android - 设置 chromium depot_tools 时无法运行 fetch android
- ruby-on-rails - rails delay_jobs + 删除记录
- php - 删除在 $_COOKIE 中编码的 JSON 元素
- geoserver - vec:Geoserver 的 SLD 中的 BarnesSurface
- php - 如何在具有最大长度和最大数组总和的数组中插入随机值
- bash - bash 从表中提取第一行
- java - 将带有 ksoap2 的自定义标头发送到 asp.net
- powershell - 对象引用未设置为 powershell 中的对象实例