错误用Python编写CSV

时间:2011-09-17 03:10:49

标签: python csv file-io numpy

我在使用python编写的.csv文件中遇到错误(必要的格式,因为我在一个依赖于.csvs的团队中)。以非图案化的方式,在数百个1g文件中存在错误。例如,额外的10列只有1行,额外的行有错误的输入,某些行缺少~10列。我重新运行了两次相同的脚本,并且在第二次运行时没有错误。我需要一种方法来确保正确编写这些文件。这是我正在使用的代码(我知道它不是最有效的,但我知道如何以这种方式进行,我想发布它是如何做到的)。

# Sample inputs, representative of the actual data I'm working with.  
output = np.zeros([40000, 1000]) # for example
iso3 = 'ALB'
sex = 'M'
year = np.ones(40000)
post_env = np.repeat(10, 40000)
post_cause = np.repeat('a', 40000)
post_pop = np.repeat(100, 40000)
outsheet = np.zeros([output.shape[0], output.shape[1]+7], dtype='|S20')
outsheet[:, 0] = iso3
outsheet[:, 1] = sex
outsheet[:, 2] = np.array(post_year, dtype='|S20')
outsheet[:, 3] = np.array(post_age, dtype='|S20')
outsheet[:, 4] = np.array(post_cause, dtype='|S20')
outsheet[:, 5] = np.array(post_env, dtype='|S20')
outsheet[:, 6] = np.array(post_pop, dtype='|S20')
outsheet[:, 7:] = np.array(output, dtype='|S20')

outsheet[outsheet=='nan'] = '.'
first_row = ['draw' + str(i) for i in range(output.shape[1])]
first_row.insert(0, 'population')
first_row.insert(0, 'envelope')
first_row.insert(0, 'cause')
first_row.insert(0, 'age')
first_row.insert(0, 'year')
first_row.insert(0, 'sex')
first_row.insert(0, 'iso3')
outfile = open('filename', 'w')
writer = csv.writer(outfile)
writer.writerow(first_row)
writer.writerows(outsheet)
outfile.close()

错误甚至包括第一列中的随机数值(应该都是'ALB'),观察的一组额外行和观察缺失的列(写后)。

1 个答案:

答案 0 :(得分:3)

另外,使用xrange代替范围通常更快。

您是否完全确定运行该作业的计算机上的内存和磁盘是否良好?由于您的数据范围可达数百GB,因此您看到基于硬件的损坏并不是不可能的。即使机器似乎稳定运行而没有崩溃,在这些数据密度下,单位内存错误也很常见。如果任何硬件是边缘的,这就是我期望的那种行为。

您的磁盘是否运行校验和搜索格式? (ZFS是我最喜欢的)你在使用ECC内存吗?白天很热的时候你会看到更多的错误吗?您是在机器上看到这些错误,还是在通过网络传输后看到这些错误?

您的手术需要多长时间才能运行?你到底看到了更多的错误吗?