繁体   English   中英

如何将字符串和数字列表转换为在 python 中浮动?

[英]How to convert a list of strings and numbers to float in python?

我需要从 csv 文件中获取数据,我已经完成并将数据附加到列表中,但不知道如何将整个列表变成浮点数。

我尝试了以下代码,但它不起作用:

import csv 

with open('csv1.csv', 'r') as f:
    lines = f.readlines()[6]
    new_list = []
    for i in lines:
        print(lines)
        new_list.append(float(i))
        print(new_list)

我收到一条 ValueError 消息。 ValueError: could not convert string to float: '"' 这很奇怪,因为我不明白它从哪里得到 "。

我正在使用的 CSV 文件来自经济局,这是我正在使用的确切文件的链接: https://apps.bea.gov/iTable/iTable.cfm?reqid=19&step=2#reqid=19&step=2&isuri =1&1921=调查

当您执行lines = f.readlines()[6]时,您只会抓取文件的第七行。 那只是一行,它是一个str (字符串),其中包含文件中的整行。 当您通过 go 并尝试迭代for i in lines逐个字符地遍历文件的第七行并尝试进行float()转换。 该行的第一个字符是导致错误的"

为了 go 通过文件的所有行从第七行开始,您需要将数组索引更改为lines = f.readlines()[6:] 这让你一个接一个地处理这些行。

但是,这只是对正在发生的事情的一种解释。 正如@Razzle Shazl 指出的那样,您没有使用 CSV 阅读器。

也就是说,我认为这就是你真正想要完成的事情:

import csv

with open('csv1.csv', 'r') as f:
    csv_data = csv.reader(f, delimiter=',', quotechar='"')

    for i in range(6):  # this is to skip over header rows in the data (I saw 6 in the file I downloaded)
        next(csv_data)

    for row in csv_data:  # going through the rest of the rows of data
        new_list = []
        for i in range(2, len(row)):  # go through each column after the line number and description
            new_list.append(float(row[i]))  # convert element to float and append to array
        print(f"CSV Input: {row}")
        print(f"Converted: {new_list}")

您不能将空字符串转换为浮点数。 可能某处数据为空。

In [1]: float("")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-603e80e58999> in <module>
----> 1 float("")

ValueError: could not convert string to float:

如果要忽略异常并继续处理,请使用try/except

暂无
暂无

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

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