![](/img/trans.png)
[英]Python dataframe how to group by one column and get sum of other column
[英]How to sum a column in python without calling it a dataframe
我有输出到csv文件中的数据,例如:
url date id hits
a 2017-01-01 123 2
a 2017-01-01 123 2
b 2017-01-01 45 25
c 2017-01-01 123 5
d 2017-01-03 678 1
d 2017-01-03 678 7
依此类推,点击数是ID值在每个网址的给定日期出现的次数。 (即:ID号123在网址“ a”上于2017年1月1日出现2次。
我需要在命中后创建另一列,称为“总命中”,以捕获给定url,日期和id值每天的总命中数。 所以输出看起来像这样。
url date id hits total_hits
a 2017-01-01 123 2 4
a 2017-01-01 123 2 4
b 2017-01-01 45 25 25
c 2017-01-01 123 5 5
d 2017-01-03 678 1 8
d 2017-01-03 678 7 8
如果有解决方案而不使用pandas或numpy,那将是惊人的。
请帮忙! 提前致谢。
使用标准python安装简单。
collections.defaultdict(int)
来计算url / date / id三元组的出现 像这样:
import collections,csv
d = collections.defaultdict(int)
rows = []
with open("input.csv") as f:
title = next(f).split() # skip title
for line in f:
toks = line.split()
d[toks[0],toks[1],toks[2]] += int(toks[3])
rows.append(toks)
# complete data
for row in rows:
row.append(d[row[0],row[1],row[2]])
title.append("total_hits")
with open("out.csv","w",newline="") as f:
cw = csv.writer(f)
cw.writerow(title)
cw.writerows(rows)
这是输出文件:
url,date,id,hits,total_hits
a,2017-01-01,123,2,4
a,2017-01-01,123,2,4
b,2017-01-01,45,25,25
c,2017-01-01,123,5,5
d,2017-01-03,678,1,8
d,2017-01-03,678,7,8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.