gpt4 book ai didi

Python:将输出保存到 csv 文件时出错?

转载 作者:太空宇宙 更新时间:2023-11-03 16:54:25 26 4
gpt4 key购买 nike

我仅在使用 MS Excel 打开时才意识到此错误,但在使用 Notepad++ 打开时则正常。当我使用 Excel 打开时,这些值不在相应的列中。我有以下代码,它帮助我仅根据binary.csv中的值1进行乘法并输出排除binary.csv中所有0值的值。谁能帮我吗?

二进制.csv

0,1,0,0,1,0,1,0,0
1,0,0,0,0,1,0,1,0
0,0,1,0,1,0,1,0,0

real.csv

0.1,0.2,0.4,0.1,0.5,0.5,0.3,0.6,0.3

代码

import csv

with open('real.csv', 'rb') as csvfile:
for row in csv.reader(csvfile, delimiter=','):
reals = row

with open('binary.csv', 'rb') as csvfile:
pwreader = csv.reader(csvfile, delimiter=',')

with open('onehothot.csv','wb') as testfile:
csv_writer=csv.writer(testfile)
for row in pwreader:
result = []

for i,b in enumerate(row):
if b == '1' :
result.append(reals[i])

c= ",".join(result)
print(c)
csv_writer.writerow([c])

使用 Notepad++ 打开 csv 文件输出

0.2,0.5,0.3
0.1,0.5,0.6
0.4,0.5,0.3

使用 MS Excel 打开 csv 文件中所需的输出(填充 3 行 3 列)

0.2 0.5 0.3
0.1 0.5 0.6
0.4 0.5 0.3

我使用 MS Excel 打开的实际 CSV 输出文件为 3 行 1 列,因为“0.2 0.5 0.3”被视为单个实体。因此,Excel 中仅显示 3 个实体。

最佳答案

无需尝试通过加入 , 来创建每一列,因为 csv 库将为您执行此操作,而是按如下方式进行编码:

import csv

with open('real.csv', 'rb') as csvfile:
for row in csv.reader(csvfile, delimiter=','):
reals = row

with open('binary.csv', 'rb') as csvfile:
pwreader = csv.reader(csvfile, delimiter=',')

with open('onehothot.csv','wb') as testfile:
csv_writer=csv.writer(testfile)
for row in pwreader:
result = []

for i,b in enumerate(row):
if b == '1' :
result.append(reals[i])

csv_writer.writerow(result)

关于Python:将输出保存到 csv 文件时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35548999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com