3

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.

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

I tried a little bit to find a existing function to do that, but also could not.. your function is good, but not versatile. For instance, cannot handle two dimensional array. But give you up-vote for your prompt reply, man
Hi Vindicate, you did not specify you want something that works for more dimensions. Based on you example the answer given before would work perfectly for you. Without tweaking too much, I edited the solution and now it works for as many dimensions you want. Hope it helps.
it's great man, just hoping they could develop a method of conditional conversion.
2

For arrays of mixed datatypes set dtype=object:

>>> mix = numpy.array(['1.', '2.', 'a'])
>>> mixed=[]
>>> for a in list(mix):
       try:
         mixed.append(float(a))
       except:
         mixed.append(a)

>>> mixed=numpy.array(mixed, dtype=object)
>>> mixed
array([1.0, 2.0, 'a'], dtype=object)
>>> type(mixed[0]),type(mixed[1]),type(mixed[2])
(<type 'float'>, <type 'float'>, <type 'numpy.string_'>)

Hope it hepls.

Comments

0

One way that might work is checking if the string matches a number with a regex, and if so convert to float:

[float(x) if re.search('[0-9]*\.?[0-9]', x) else x for x in mix]

Comments