0

我在 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

4 回答 4

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)])])
于 2013-09-27T14:01:30.707 回答
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
于 2013-09-27T13:29:58.497 回答
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。

于 2013-09-27T13:12:48.827 回答
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))

需要帮助请叫我。

于 2013-09-27T14:56:02.143 回答