Home > Mobile >  Convert all my values in array to float python
Convert all my values in array to float python

Time:01-02

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?

CodePudding user response:

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'>

CodePudding user response:

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]]
  • Related