Python 基于列输入的随机数计算总和并导出到文件

Python 基于列输入的随机数计算总和并导出到文件,python,Python,这是我以前请求()的重新发布。但在这个问题上,我要求在不使用pandas库的情况下提供解决方案 问题和以前一样。我需要对File1的col1的每个值的“value”列amount求和,并将其导出到输出文件。我是python新手,需要对数千条记录执行此操作 文件1 期望输出: 提前谢谢 由于权限问题,我无法使用pandas库。我尝试了以下代码。分享我迄今为止的努力: import csv fin = open("File1.txt","r") list_txid = {} amount_tx =

这是我以前请求()的重新发布。但在这个问题上,我要求在不使用pandas库的情况下提供解决方案

问题和以前一样。我需要对File1的col1的每个值的“value”列amount求和,并将其导出到输出文件。我是python新手,需要对数千条记录执行此操作

文件1 期望输出: 提前谢谢

由于权限问题,我无法使用pandas库。我尝试了以下代码。分享我迄今为止的努力:

import csv 
fin = open("File1.txt","r")
list_txid = {}
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:
    amount_tx[txid] += amount
    print("{0}\t{1:d}\n".format(txid, amount_tx[txid]))

您可以在python中使用pandas库

它具有对行进行分组和对所需列求和的功能

import pandas as pd
df = pd.read_excel("File1.txt")

print df.groupby(['col1'])[["value"]].sum()

也许这不是最好的方法,但考虑到你不能使用熊猫:这很有效

import csv
fin = open("File1.txt","r")
# skip the first line
next(fin)

amount_tx = {}

for line in fin:
    # make the line into a list of the form ['x', 'y', 'z', 'a']
    line = line.rstrip()
    f = line.split("\t")
    g = f[0].split()

    # get the two variables necessary
    txid = g[0]
    amount = int(g[3])

    # add to dictionary if not yet present
    if txid not in amount_tx:
        amount_tx[txid] = 0
    amount_tx[txid] += amount

fin.close()

for txid in amount_tx:

    print("{0}\t{1:d}\n".format(txid, amount_tx[txid]))

你会用numpy吗?如果不是,那么问题似乎是在文件的迭代过程中没有更新值

现在,对于文件的读取:

with open('File1.txt') as fin:
    reader = csv.reader(fin, delimiter='\t')
这是我建议打开它的方式。注意,您不需要将“r”指定为模式(open的第二个变量),因为默认情况下是这样。与“fin=open”相反,“with open”命令的作用是在缩进后自动关闭文件。您保存了两行代码,更重要的是,如果您忘记键入fin.close()-毕竟它不会在代码中抛出错误-文件无论如何都是关闭的

reader=csv。reader(fin,delimiter='\t')基本上会自动从末尾剥离空白,并按制表符空间进行拆分

下面是我将如何整体更改您的代码

import csv
amount_tx = {}

with open('File1.txt') as fin:
    reader = csv.reader(fin, delimiter='\t')
    for f in reader:
        txid, amount = f[0], int(f[3])
        try:
            amount_tx[txid] += amount
        except KeyError:
            amount_tx[txid] = amount

with open('OutputFileName.txt','w') as w:
    for txid, amount in amount_tx.items():
        w.write('%s\t%d\n' % (txid, amount))
如果您使用的是python 2.X而不是3.X,那么amount\u tx.items()应该是amount\u tx.iteritems()

“OutputFileName.txt”应替换为要保存结果的文件名 open(FNAME,'w')指定您正在写入文件而不是读取文件(首先删除/重新创建文件,如果要保留文件并附加到文件,请改用“a”)

输出:

col1    Sum

559 2500000000
558 100000000
557 3000000000

与其他答案类似,但使用默认设置为整数,如果字典中没有键,则可以求和

from collections import defaultdict
import csv

with open('file1.txt') as fin:
    reader = csv.reader(fin, delimiter='\t')

    amount_tx = defaultdict(int)
    # Skip headers
    next(reader)
    for line in reader:
        key = line[0]
        amount_tx[key] += int(line[3])

with open('OutputFile.txt','w') as w:
    # Write new headers
    w.write("Col1   Sum\n")
    for tx_id, tx_amount in amount_tx.items():
        w.write("{0}\t{1:d}\n".format(tx_id,tx_amount))

不幸的是,问题中说他们不能使用熊猫。谢谢你的建议。但我不能使用问题中提到的熊猫图书馆。可能的副本(请检查:)
import csv 
fin = open("File1.txt","r")
list_txid = {}
for line in fin:
    line = line.rstrip()
    f = line.split()
    if('value' not in f):
      try:
        list_txid[f[0]]+=int(f[3])
      except:
        list_txid[f[0]]=int(f[3])
fin.close()
print("{0}\t{1}\n".format('col1', 'Sum'))
for k,v in list_txid.items():
    print("{0}\t{1:d}".format(k, v))
col1    Sum

559 2500000000
558 100000000
557 3000000000
from collections import defaultdict
import csv

with open('file1.txt') as fin:
    reader = csv.reader(fin, delimiter='\t')

    amount_tx = defaultdict(int)
    # Skip headers
    next(reader)
    for line in reader:
        key = line[0]
        amount_tx[key] += int(line[3])

with open('OutputFile.txt','w') as w:
    # Write new headers
    w.write("Col1   Sum\n")
    for tx_id, tx_amount in amount_tx.items():
        w.write("{0}\t{1:d}\n".format(tx_id,tx_amount))