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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With