0

I would like to convert the following matrix (string) to float numbers

           0                0                0                0                0
            0                0                0                0       78.2949219
   81.0840607       83.2369537   0.000100000005       101.055199       78.5405502

i used:

import numpy as np
number = []
for line in filename:
    number.append(line)
number = np.array(number)
number_float = number.astype(np.float)

but it gives me: ValueError: could not convert string to float: ' 0 0 0 0 0\n' is that because \n ?

3
  • 1
    You need to split the line into separate elements for each number. Commented Jan 28, 2020 at 22:05
  • are you trying to read a fulolile? Perhaps numpy.loadtxt could be useful? Commented Jan 28, 2020 at 22:06
  • thank you! split works! Commented Jan 28, 2020 at 22:11

1 Answer 1

1

You don't have a 2-dimensional matrix, you just have a list of strings, with one element for each line. You need to split it into separate numbers.

for line in filename:
    number.append(line.split())

You can also do the float conversion at the same time, and you can build the list using a list comprehension.

number = [[float(cell) for cell in line] for line in filename]
Sign up to request clarification or add additional context in comments.

3 Comments

I think it is better to use list-comprehension instead of map (or of course, list(map(...))) as map returns a map object and not a list (not sure how np.array handles map objects)
@Tomerikoo Always forget that detail about map. I've converted to nested list comprehensions.
Sorry to be annoying haha but now you just forgot to split the line

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.