简体   繁体   中英

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

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.

>>> 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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