Luke Katfish Daniels
Luke Katfish Daniels

Reputation: 15

Turning strings in a list into floats

I have created a function that sorts through a csv file and returns lists into tuples however the items in the lists are string, how do I convert them to floats?

I need to do calculations with this data such as mean, median etc.

def load_data(filename):
    datasets = []
    for line in open(filename):
        line = line.strip().split(",")
        dataset = ((line[0],line[1:]))
        datasets.append(dataset)

    return datasets

At the moment my data looks like this when printed ('Slow Loris', [' 21.72', ' 29.3', ' 20.08', ' 29.98',...... etc how do I remove the ' ' around the numbers

Upvotes: 1

Views: 904

Answers (3)

Ben
Ben

Reputation: 99

Use the float() function to typecast it as a float.

Per this link: Parse String to Float or Int

Upvotes: 1

mmachine
mmachine

Reputation: 926

def load_data(filename):
    datasets = []
    for line in open(filename):
        line = line.strip().split(",")    
        floats = [float(x) for x in line[1:]]
        dataset = ((line[0],floats))
        datasets.append(dataset)
    return datasets

Upvotes: 1

m_callens
m_callens

Reputation: 6360

You could make a new list and append the casted type like so...

list_of_floats = list()
for item in list_of_strings:
    list_of_floats.append(float(item))

Or iterate through each value and change it at its current position...

for i in range(len(list_of_strings)):
    list_of_strings[i] = float(list_of_strings)

Upvotes: 1

Related Questions