python安装csv出错,用Python编写csv时出错

我在用python编写的.csv文件中遇到错误(这是必需的格式,因为我所在的团队依赖于.csv)。以非模式化的方式,在数百个1g文件中会出现错误。例如,只有1行的额外10列,有固定输入的额外行,某些行缺少~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')、一组额外的观察行和一个观察缺失的列(写后)。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值