在 Python 中将字符串转换为浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16161082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:54:59  来源:igfitidea点击:

Convert string to float in Python

pythonstringfloating-point

提问by JupiterOrange

I have a csv file and I am trying to plot some of the contents and need to convert the strings to floats. My problem is the following:

我有一个 csv 文件,我正在尝试绘制一些内容,需要将字符串转换为浮点数。我的问题如下:

When I run the code below,

当我运行下面的代码时,

with open('meteors.csv', 'rU') as csvfile:
    reader=csv.reader(csvfile)
    for row in reader:    
        print row[6]

I get this output:

我得到这个输出:

58.58333

When I instead try

当我尝试

print type(row[6])

I get this output:

我得到这个输出:

<type 'str'>

But when I try

但是当我尝试

 print float(row[6])

I get this error:

我收到此错误:

ValueError: could not convert string to float: coordinate_1

Anyone know what's going on?

有谁知道这是怎么回事?

采纳答案by Burhan Khalid

Most likely you are seeing the first row, which has the column headers on your CSV file, and coordinate_1is a header.

您很可能会看到第一行,它在您的 CSV 文件中有列标题,并且coordinate_1是一个标题。

You can either skip the first row:

您可以跳过第一行:

with open('meteors.csv', 'rU') as csvfile:
    reader=csv.reader(csvfile)
    reader.next() # skips the first (header) row
    for row in reader:    
        print row[6]

Or, use DictReader, like this:

或者,DictReader像这样使用:

with open('meteors.csv', 'rU') as csvfile:
    reader=csv.DictReader(csvfile)
    for row in reader:    
        print row['coordinate_1']

回答by Blender

Your CSV file probably has a header that lists the name of each column. You can't convert those names into floats, so that's where your error is coming from.

您的 CSV 文件可能有一个标题,其中列出了每列的名称。您无法将这些名称转换为floats,因此这就是您的错误的来源。

You have to consume the header first:

您必须首先使用标头:

with open('meteors.csv', 'rU') as csvfile:
    reader = csv.reader(csvfile)
    header = next(reader)

    for row in reader:
        print float(row[6])