Reputation:
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.
Upvotes: 3
Views: 5520
Reputation: 5914
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]
Upvotes: 0
Reputation: 2190
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
Upvotes: 5
Reputation: 8709
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.
Upvotes: 2