Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Convert String to Float when Possible

Suppose I have a list

mix = numpy.array(['1.', '2.', 'a'])

How can I convert string to float when possible, so that I could get:

array([1., 2., 'a'])

I try to use try / exception with astype(), but it won't convert a single element.

Update: In csv package, there is csv.QUOTE_NONNUMERIC, I am wondering if numpy supports something similar.


1 Answers

Didn't find a function to make it work, so I wrote something that works for you.

def myArrayConverter(arr):

    convertArr = []
    for s in arr.ravel():    
        try:
            value = float32(s)
        except ValueError:
            value = s

        convertArr.append(value)

    return array(convertArr,dtype=object).reshape(arr.shape)

Cheers

like image 50
mrcl Avatar answered May 01 '26 05:05

mrcl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!