以CSV格式汇总所有值

时间:2015-02-12 20:03:55

标签: python csv sum

我有一个包含01的CSV文件,需要确定整个文件的总和。在ExCel中打开文件时看起来像这样:

0 1 1 1 0 0 0 1 0 1
1 0 1 0 0 1 1 0 0 0
0 0 1 0 0 0 0 1 0 1
0 1 1 1 1 1 1 0 1 1
0 0 1 0 1 0 1 1 0 1
0 0 0 0 0 0 0 0 1 0
0 0 1 0 0 1 1 0 1 1
0 0 1 1 0 0 1 1 0 1
1 0 1 0 1 0 1 1 1 0
0 1 0 0 1 0 0 0 1 1

使用此脚本,我可以将每行的值相加,然后将它们打印在一列中:

import csv 

import numpy as np

path = r'E:\myPy\one_zero.csv' 

infile = open(path, 'r')

with infile as file_in: 
    fin = csv.reader(file_in, delimiter = ',') 
    for line in fin: 
        print line.count('1')

我需要总结一下结果列,但我对此的体验很温和。寻找建议。感谢。

3 个答案:

答案 0 :(得分:1)

如果你有超过1和0的地图到int并且总和所有行:

with open( r'E:\myPy\one_zero.csv') as f:
     r = csv.reader(f, delimiter = ',') 
     count = sum(sum(map(int,row)) for row in r)

或只计算1:

with open( r'E:\myPy\one_zero.csv' ) as f:
     r = csv.reader(f, delimiter = ',')
     count = sum(row.count("1") for row in r)

只需使用with open(r'E:\myPy\one_zero.csv'),您就不需要也不应该打开,然后将文件句柄传递给。

答案 1 :(得分:0)

path = r'E:\myPy\one_zero.csv' 
infile = open(path, 'r')
answer = 0
with infile as file_in: 
   fin = csv.reader(file_in, delimiter = ',') 
   for line in fin: 
      a = line.count(1)
      answer += a
print answer

示例:

answer = 0
lines = [[1, 0, 0, 1],[1,1,1,1],[0,0,0,1]]
for line in lines:
   a = line.count(1)
   answer += a
print answer
7

您使用了一个可能的错误:

line.count('1')

VS

line.count(1)

寻找字符串而不是数字

答案 2 :(得分:0)

为什么要使用CSV模块?你有一个文件,包括0s,1s,逗号和换行符。只需打开文件,读取()并计算1:

>>> with open(filename, 'r') as fin: print fin.read().count('1')

那应该能得到你想要的东西,不是吗?