我只有在使用MS Excel打开时才会意识到这个错误,但是在使用Notepad ++打开时它很好。当我使用Excel打开时,这些值不在相应的列中。我有以下代码,它帮助我只根据binary.csv中的值1进行乘法,并输出值,不包括binary.csv中的所有0值。任何人都可以帮助我吗?
binary.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个实体。
答案 0 :(得分:1)
无需尝试通过加入,
来创建每个列,因为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)