简体   繁体   中英

how to add a column to a csv file that is the sum of the rows and a row that is the sum of the columns

I have data in a csv file eg

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

what I want is to create an extra column that sums the first rows so that the result will look like.

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

And an extra row that sums the columns.

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

This is probably really basic but I could do with the help please?

#!/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))

I know, I'm treating Python like Haskell these days.

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
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)])])

How about some pythonic list comprehension:

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))

Let me know if you need anything else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM