Reputation: 552
So I am trying to run this piece of code:
reader = list(csv.reader(open('mynew.csv', 'rb'), delimiter='\t'))
print reader[1]
number = [float(s) for s in reader[1]]
inside reader[1] i have the following values:
'5/1/2013 21:39:00.230', '46.09', '24.76', '0.70', '0.53', '27.92',
I am trying to store each one of values into an array like so:
number[0] = 46.09
number[1] = 24.09
and so on.....
My question is: how would i skip the date and the number following it and just store legitimate floats. Or store the contents in an array that are separated by comma?
It throws an error when I try to run the code above:
ValueError: invalid literal for float(): 5/1/2013 21:39:00.230
Thanks!
Upvotes: 0
Views: 131
Reputation: 395
number = []
for s in reader[1]:
number.append(int(float(s)))
this will convert string into exact float
Upvotes: 0
Reputation: 4144
Or you can search for / in the string and pass if exists, something like this
my_list_results = []
my_list = ['5/1/2013 21:39:00.230', '46.09', '24.76', '0.70', '0.53', '27.92']
for m in my_list:
if '/' not in m: #if we don't find /
my_list_results.append(m)
print my_list_results
Upvotes: 0
Reputation: 5218
If it's always the first value that's not a float, you can take it out doing:
reader = list(csv.reader(open('mynew.csv', 'rb'), delimiter='\t'))
print reader[1]
number = [float(s) for s in reader[1][1:]]
Upvotes: 0
Reputation: 59604
Just skip values which cannot be converted to float:
number = []
for s in reader[1]:
try:
number.append(float(s))
except ValueError:
pass
Upvotes: 5