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

I need to get data from a csv file which I have done and have appended the data to a list but don’t know how to make the entire list into a float.

I tried the following code and it did not work:

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)

I got a ValueError message. ValueError: could not convert string to float: ‘”‘ which is weird since I don’t understand where it is getting the ” from.

The CSV file I am using is from Bureau Of Economic, here’s the link to the exact file I am using: https://apps.bea.gov/iTable/iTable.cfm?reqid=19&step=2#reqid=19&step=2&isuri=1&1921=survey

Answer

When you execute lines = f.readlines()[6] you are grabbing only the seventh line of the file. That is only one line and it is a str (string) that contains that whole line from the file. As you go through and try to iterate for i in lines you are actually going through the seventh line of the file, character-by-character and attempting to do the float() conversion. The first character of that line is the " which is causing the error.

In order to go through all of the lines of the file starting with the seventh line you need to change the array indexing to lines = f.readlines()[6:]. That gets you to processing the lines, one-by-one.

But, that’s all a sort of explanation of what was going on. As @Razzle Shazl points out, you’re not using the CSV reader.

That said, I think this is what you’re actually trying to accomplish:

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}")

Leave a Reply

Your email address will not be published. Required fields are marked *