Numpy Convert String to Float if possible
Suppose I have a list
mix = numpy.array(['1.', '2.', 'a'])
How can I convert a string to float when possible so that I can get:
array([1., 2., 'a'])
I am trying to use try / exception
with astype()
but will not convert a single item.
Thank!
Update: The package csv
does csv.QUOTE_NONNUMERIC
, I am wondering if numpy
it supports something like this.
+3
source to share
3 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)
Greetings
+4
source to share
For arrays of mixed data types, 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 will be.
+2
source to share