使用Python从csv文件中删除空行

时间:2017-03-29 15:47:49

标签: python

我正在创建一个代码,用于计算前5行的平均值。但是,如果最初是空的,我想不出删除行的方法。这是我的代码草图。对不起,如果它是原始的,我仍然是新手。谢谢!

import csv
import statistics
with open('Test.csv') as file:
 data=csv.reader(file,delimiter=',')

 sample1=[]
 sample2=[]
 sample3=[]
 sample4=[]
 sample5=[]
 #I was trying to do something like that but then
 #I receive error message that states that statistics.mean requires at least
 #one value.
 #(for row in data:
    #if row:
        #some=row[1])
 for row in data:

    sp1=row[0]
    sample1.append(sp1)
    sample1=[int(x) for x in sample1]
    sp2=row[1]
    sample2.append(sp2)
    sample2=[int(x) for x in sample2]
    sp3=row[2]
    sample3.append(sp3)
    sample3=[int(x) for x in sample3]
    sp4=row[3]
    sample4.append(sp4)
    sample4=[int(x) for x in sample4]
    sp5=row[4]
    sample5.append(sp5)
    sample5=[int(x) for x in sample5]

 mean1=statistics.mean(sample1)
 mean2=statistics.mean(sample2)
 mean3=statistics.mean(sample3)
 mean4=statistics.mean(sample4)
 mean5=statistics.mean(sample5)
 print(mean1)
 print(mean2)
 print(mean3)
 print(mean4)
 print(mean5)

1 个答案:

答案 0 :(得分:1)

这是一种更简洁的方法:

import csv
import statistics

fromFile = []
with open('sample.csv','r') as fi:
    data=csv.reader(fi,delimiter=',')
    first = True
    for row in data:
        if first:
            first = False
            continue
        if not filter(lambda a: a != '', row):
            continue
        fromFile.append(row)
print statistics.mean([int(item[1]) for item in fromFile])

示例CSV文件:

name, age
bob,9
rachel,90


,,,,
joe,5