根据一列中输入的随机数求和 [英] Summing up the total based on the random number of inputs of a column
问题描述
我需要总结File1的col1的每个值的值列数量,并将其导出到输出文件。我是python的新手,需要做成千上万的记录。
I need to sum up the "value" column amount for each value of col1 of the File1 and export it to an output file. I'm new in python and need to do it for thousands of records.
col1 col2 value
559 1 91987224 2400000000
559 0 91987224 100000000
558 0 91987224 100000000
557 2 87978332 500000000
557 1 59966218 2400000000
557 0 64064811 100000000
所需输出:
Desired Output:
col1 Sum
559 2500000000
558 1000000000
557 3000000000
谢谢。
PS:由于权限问题,我无法使用pandas库。我尝试了以下方法码。与追溯共享:
P.S : I can't use the pandas library due to permission issues.I tried the following code. Sharing it with trace backs:
import csv
fin = open("File1.txt","r")
list_txid = {}
num_tx = {}
amount_tx = {}
for line in fin:
line = line.rstrip()
f = line.split("\t")
txid = f[0]
amount = int(f[3])
fin.close()
for txid in list_txid:
num_tx[txid] += 1
amount_tx[txid] += amount
print("{0}\t{1:d}\t{2:d}".format(txid, amount_tx[txid]))
跟踪:
回溯(最近一次通话最近):
文件 C:\Users .... \sum.py,第14行,在$ b中$ b金额= int(f [3])
IndexError:列表索引超出范围
Traceback :
Traceback (most recent call last): File "C:\Users....\sum.py", line 14, in amount = int(f[3]) IndexError: list index out of range
推荐答案
使用 read_csv
创建 DataFrame
,然后 groupby
按 level = 0
并汇总总和
。上次导出 to_csv
:
Use read_csv
for create DataFrame
, then groupby
by index by level=0
and aggregate sum
. Last export to_csv
:
df = pd.read_csv(file1)
df.groupby(level=0)['value'].sum().to_file(file2)
这篇关于根据一列中输入的随机数求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!