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

3
  • 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
    – user2558887
    Oct 29, 2014 at 19:43
  • 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.
    – mrcl
    Oct 30, 2014 at 2:25
  • it's great man, just hoping they could develop a method of conditional conversion.
    – user2558887
    Oct 31, 2014 at 16:20
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.

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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.