0

我正在尝试打开一个 10 列 x 100 行的 csv 文件,我首先想将其交换为 100 列 x 10 行,我相信我正确使用了 zip 函数,然后使用 100 个浮点数制作 10 个数组每一个。

output = []
with open("undercurve.csv",'rU') as f5:
    reader = csv.reader(f5, delimiter= ',')
    reader1 = zip(*reader)
    for row in reader1:
        value = 0 
        for i in row:
            value = float(i)
            output.append(i)

但是,当我运行它时,我得到一个

    ValueError
    Traceback (most recent call last)

        174             else:
        175                 filename = fname
    --> 176             exec compile(scripttext, filename, 'exec') in glob, loc
        177     else:
        178         def execfile(fname, *where):

    C:\Users\Robert\Downloads\May.py in <module>()
        142         value = 0
        143         for i in row:
    --> 144             value = float(i)
        145             output.append(i)
        146 
    ValueError: could not convert string to float. 

我猜这是来自上一部分:

i = 0
with open("undercurve.csv",'w') as f3:
    for i in undercurve_1:
        mean = i
        variance = .2
        points = undercurve(1000)[:10]
        for item in points:
            x = str(item)
            f3.write(x + ",")
        f3.write("\n")     

如果我尝试使用 x = float(item),则会出现错误:

    TypeError                                 
    Traceback (most recent call last)
    174             else:
    175                 filename = fname
--> 176             exec compile(scripttext, filename, 'exec') in glob, loc
    177     else:
    178         def execfile(fname, *where):

C:\Users\Robert\Downloads\May.py in <module>()
    130         for item in points:
    131             x = float(item)
--> 132             f3.write(x + ",")
    133         f3.write("\n")
    134 
    TypeError: unsupported operand type(s) for +: 'float' and 'str'. 

我不确定在这种情况下该怎么做。

0.485863651248,0.0387115424974,0.287431660408,0.368734594828,0.618990463984,0.112220965205,0.418700402941,0.193754757929,0.573411295973,-0.192370410069,
-1.42282833703,-1.52808081061,-1.03071829996,-1.00330662742,-1.23896275168,-1.09742340137,-0.940839402591,-0.918657969034,-1.37832945051,-0.932452513278,

这些只是 undercurve.csv 文件的前 2 行

4

1 回答 1

1

显然,文件每一行的结尾都以逗号结尾。这会出现一个''(空字符串)。并且 float('') 给你 ValueError。

于 2013-05-27T22:53:15.733 回答