1

I am using Numpy and I have a matrix like the following:

[["5","6"],
["3","4.5"]]

How can I convert all these values to float?

2 Answers 2

2

Try numpy.ndarray.astype(float). Read more here.

NOTE: This is not an in place operation so remember to set it back to a variable

import numpy as np

arr = np.array([["5","6"],
                ["3","4.5"]])

arr = arr.astype(float)  #<--- 

print(arr)
print(type(arr[0,0])) #printing type of a single element in the matrix
array([[5. , 6. ],
       [3. , 4.5]])

<class 'numpy.float64'>
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a way to do it inplace without extra lib/module:

ll = [["5","6"], ["3","4.5"]]

def transform(ll):
    for i in range(len(ll)):
        if type(ll[i])==str:
            ll[i]=float(ll[i])
        elif type(ll[i])==list:
            transform(ll[i])
    return ll

print(transform(ll))

output is:

[[5.0, 6.0], [3.0, 4.5]]

2 Comments

while a valid approach, OP is using NumPy array already (as mentioned in question and tag), so it's not an extra module.
right, but code was incomplete in the question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.