如何将列添加到作为行总和的csv文件和作为列总和的行

时间:2013-09-27 13:00:21

标签: python csv sum

我在csv文件中有数据,例如

1,2,3,4
4,5,6,7

我想要的是创建一个额外的列,对第一行求和,以便结果看起来像。

1,2,3,4,10
4,5,6,7,22

一个额外的行,用于对列进行求和。

1,2,3,4,10
4,5,6,7,22
5,7,9,11,32

这可能是非常基本但我可以帮忙吗?

4 个答案:

答案 0 :(得分:0)

#!/usr/bin/python

import sys
from itertools import imap, repeat
from operator import add

total = repeat(0) # See how to handle initialization without knowing the number of columns ?

for line in sys.stdin:
    l = map(int, line.split(','))
    l.append(sum(l))
    print ','.join(map(str,l))
    total = imap(add, total, l)
print ','.join(map(str, total))

我知道,这些天我像Haskell一样对待Python。

答案 1 :(得分:0)

import csv

thefile = ["1,2,3,4","4,5,6,7"]
reader = csv.reader(thefile)

temp = []
final = []

# read your csv into a temporary array
for row in reader:
    temp.append([int(item) for item in row])
# add a row for sums along the bottom
temp.append(final)
for item in temp[0]:
    final.append(0)




for row in temp:
    sum = 0
    for index, item in enumerate(row):
        sum += item  #total the items in each row
        temp[-1][index] = temp[-1][index] + item  #add each item to the column sum
    row.append(sum) #add the row sum

print temp

答案 2 :(得分:0)

import sys
import csv

def is_number(s):
    try: 
        float(s)
        return True
    except ValueError:
        return False

with open(sys.argv[2], 'wb') as writefile:
    writer = csv.writer(writefile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
    with open(sys.argv[1], 'rb') as readfile:
        reader = csv.reader(readfile, delimiter=',', quotechar='"')
        for row in reader:
            writer.writerow(row+[sum([float(r) for r in row if is_number(r)])])

答案 3 :(得分:0)

一些pythonic列表理解如何:

import csv

in_file = ["1,2,3,4","4,5,6,7"]
in_reader = list(csv.reader(in_file)) 

row_sum = [ sum(map(int,row)) for row in in_reader]      
col_sum =  [sum(map(int,row)) for row in map(list, zip (*in_file)[::2])]

for (index,row_run) in enumerate([map(int,row) for row in in_reader]):
    for data in row_run:
        print str(data)+",",
    print row_sum[index]   
for data in col_sum:     
    print str(data)+",",
print str(sum(col_sum))

如果您还有其他需要,请告诉我。