简体   繁体   English

如何将字符串列表转换为浮点数?

[英]How to convert list of strings to floats?

I am importing numbers from a csv file that looks like the picture attached: CSV File View我正在从 csv 文件中导入数字,该文件看起来像所附图片: CSV 文件视图

However, those numbers are imported as a string and not a float so I need to convert.但是,这些数字是作为字符串而不是浮点数导入的,所以我需要转换。 I've tried using this method but it just says it cannot convert.我试过使用这种方法,但它只是说它无法转换。

import csv
import numpy as np

with open('20191031-0002_09.csv', mode='r') as infile:
    reader = csv.reader(infile)
    next(reader, None)
    next(reader, None)
    next(reader, None)
    y = [columns[1] for columns in reader]

From research on stack I found this which I thought might work:从对堆栈的研究中,我发现了我认为可能有效的方法:

numbers = []
for x in y:
      numbers.extend([n for n in map(float, line.split(' '))])

However, my array still comes out as a list of strings like this:但是,我的数组仍然是这样的字符串列表:

['1.09805600', '1.09805600']

Whereas, I want it to be a array of floats.然而,我希望它是一个浮点数组。

Hope you can help.希望你能帮忙。

This is quite confusing, as pointed out above you have not declared line anywhere, but if you want to convert the string '1.09805600' to a float, simply call it a float.这很令人困惑,正如上面所指出的,您没有在任何地方声明line ,但是如果您想将字符串'1.09805600'转换为浮点数,只需将其称为浮点数。

>>> x = '1.09805600'
>>> float(x)
1.09805600

please try below:请尝试以下:

import csv
import numpy as np

with open('20191031-0002_09.csv', mode='r') as infile:
    reader = csv.reader(infile)
    y = [columns[1] for columns in reader]
    print (y)
numbers = []
numbers.extend([n for n in map(float,y)])
print (numbers)

Demo演示

if it's not work then please add your sample csv file in given demo link如果它不起作用,请在给定的演示链接中添加您的示例csv文件

If you want to convert both columns to float so that you end up with a list that looks like:如果要将列都转换为浮点数,最终得到一个如下所示的列表:

[
    [0, 1.098056],
    [.000002, 1.098056],
    etc.
]

Then this will do it:然后这将做到这一点:

import csv

with open('20191031-0002_09.csv', mode='r') as infile:
    reader = csv.reader(infile)
    next(reader, None)
    next(reader, None)
    next(reader, None)
    rows = [[float(columns[0]), float(columns[1])] for columns in reader]

If you just care about the second column:如果您只关心第二列:

    y = [float(columns[1]) for columns in reader]

Edited to handle columns with bad values:编辑以处理具有错误值的列:

import csv, sys

with open('20191031-0002_09.csv', mode='r') as infile:
    reader = csv.reader(infile)
    next(reader, None)
    next(reader, None)
    next(reader, None)
    y = []
    for columns in reader:
        try:
            y.append(float(columns[1]))
        except ValueError:
            print(f"Unable to convert '{columns[1]}'", file=sys.stderr)
            # uncomment out the next line if you want to substitute 0.0
            # y.append(0.0)

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

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