Reputation: 25
I made a list from a CSV file. It looks like this:
['18', '29', '0'...'0', '-14', '9']
It had a text element in the beginning, which I popped. Now, Python doesn't work with the list elements as with proper numbers. Whenever I try to parse the elements into floats, for example, I get the error message:
ValueError: could not convert string to float: -
My code looks like this:
list2=[[float(column) for column in row] for row in list1]
Or this:
list2 = [map(float, x) for x in list1]
Both versions produce the same result. If I try a different data type, I get messages like:
ValueError: invalid literal for int() with base 10: '-'
Can anyone tell me how do I get Python to parse the dash into a number correctly?
Upvotes: 1
Views: 1839
Reputation: 9578
It looks like the list you're creating is 1D but when you try and parse it you're treating it as a 2D list which will try converting each character in each element to a float (hence it throws an error while trying to do float('-')
). Try replacing the line with the following to fix the problem:
list2 = map(float, list1)
You should also try adding print list1
before that line to confirm that the list has the structure you think it has.
Upvotes: 7