-1

I have this csv file I want to import to python. The first row looks like this

9.98E-01    7.07E+00    2.43E+00    4.63E+00    4.16E+00    -3.22E+00   2.95E-01    

How would I convert these values to python and keep their structure(float/ decimal) I tried to convert to float but it wont let me convert string to float.

user02
  • 281
  • 3
  • 10
  • What do you mean "it wont let me convert string to float"? Show us the code you used and the full trace of the resulting error. Read [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Rory Daulton Apr 29 '17 at 22:05
  • because when I read the values into python. python reads the values as string. thats why when i tried to use float it didnt work – user02 Apr 29 '17 at 22:12

1 Answers1

1

float will do this for you. Very easy if you have a list of strings from your csv input.

>>> vals = ["9.98E-01","7.07E+00", "2.43E+00", "4.63E+00", "4.16E+00", "-3.22E+00", "2.95E-01"]
>>> map (float, vals)
[0.998, 7.07, 2.43, 4.63, 4.16, -3.22, 0.295]
Bert
  • 2,134
  • 19
  • 19
  • It should be said that in Python 3.x that will need to be `list(map(float, vals))` if you want a list. You can also use that in Python 2.x so that is a preferred way to do it. – Rory Daulton Apr 29 '17 at 22:28
  • Thanks very much ! – user02 Apr 29 '17 at 23:16
  • I tried the code but I have a list of lists so that didnt work. Any other suggestion? – user02 Apr 29 '17 at 23:22
  • my file looks something like this:[ ['5.79E+00', '1.92E+00', '6.95E+00', '3.24E+00', '3.97E+00', '1.19E+00', '6.94E-01', '3.61E+00', '3.85E+00', '-4.84E+00', '3.03E+00', '8.20E+00', '-1.31E+00', '3.18E+00', '4.81E+00'], ['-1.47E+00', '-9.52E+00', '-1.49E+01', '-6.42E+00', '-1.01E+01', '-5.81E+00', '3.23E+00', '-4.94E+00', '7.89E+00', '-4.239791947216163592e+', '', '', '', '', '']] – user02 Apr 29 '17 at 23:22