简体   繁体   English

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

[英]Python: Error saving output into csv file?

I realized this error only when open with MS Excel but it is just fine when open using Notepad++. 我仅在使用MS Excel打开时才意识到此错误,但是在使用Notepad ++打开时就很好。 The values are not in corresponding columns when I open using Excel. 使用Excel打开时,这些值不在相应的列中。 I have this following code which help me to do multiplication only according to value 1 in binary.csv and outputting values excluding all the 0 values in binary.csv. 我有以下代码,这些代码可帮助我仅根据binary.csv中的值1进行乘法,并输出不包含binary.csv中所有0值的值。 Can anyone help me? 谁能帮我?

binary.csv 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 real.csv

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

Code

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])

Output in csv file open using Notepad++ 使用记事本++打开的csv文件中的输出

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

Desired output in csv file open using MS Excel (in 3 rows and 3 columns filled) 使用MS Excel打开csv文件中的所需输出(填充3行3列)

0.2 0.5 0.3
0.1 0.5 0.6
0.4 0.5 0.3 

The actual CSV output file I open using MS Excel is in 3 rows and 1 column filled because '0.2 0.5 0.3' is treated as single entity. 我使用MS Excel打开的实际CSV输出文件分为3行和1列,因为“ 0.2 0.5 0.3”被视为单个实体。 Therefore only 3 entities displayed in Excel. 因此,在Excel中仅显示3个实体。

There is no need to try and create each column by joining with , as the csv library will do this for you, instead code it as follows: 无需尝试通过与进行连接来创建每一列,因为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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM