簡體   English   中英

str在csv python中浮動錯誤

[英]str to float error in csv python

我正在嘗試打開一個10列x 100行的csv文件,我首先想將其交換為100列x 10行,我相信我已經正確地使用了zip函數,然后用10個浮點數制作了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文件的前兩行

顯然,文件每一行的結尾都以逗號結尾。 這將顯示“”(空字符串)。 float('')為您提供ValueError。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM