1

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

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 3
    [`float`](https://docs.python.org/2/library/functions.html#float) – zero323 Sep 02 '15 at 02:24
  • mostly unrelated to the `float` issue, but you may want to consider using python's builtin [`csv`](https://docs.python.org/2/library/csv.html) module for parsing the csv file instead of doing it yourself as it will be a bit more robust. – lemonhead Sep 02 '15 at 02:37
  • possible duplicate of [Parse String to Float or Int](http://stackoverflow.com/questions/379906/parse-string-to-float-or-int) – PyNEwbie Sep 02 '15 at 02:58

3 Answers3

1

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)
m_callens
  • 6,100
  • 8
  • 32
  • 54
1
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
mmachine
  • 896
  • 6
  • 10
  • I think in this case, the first element in the tuple is a string and trying to cast as a float will give a `ValueError`. Probably want something like `dataset = (dataset[0], [float(x) for x in dataset[1])` instead – lemonhead Sep 02 '15 at 02:41
  • Or even ```dataset = ((line[0],map(float,line[1:])))``` – wwii Sep 02 '15 at 02:51
1

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

Per this link: Parse String to Float or Int

Community
  • 1
  • 1
Ben
  • 99
  • 3