2

I wanted to use the function .astype(float) to convert an array named Defocus_Array to float. But I got this error.

>>> Defocus_Array.astype(float)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: defocus

I understand that "defocus" the name of the data extracted is the problem. I tried to delete it with numpy.delete but it doesn't work. How can I delete it to convert my array? Or is it another way to convert my array? Thank you.

1
  • What do you want to do with the element containing "defocus"? Do you want it to become nan? Then just assign those values to 'nan' and they will convert to nan. Commented Nov 27, 2014 at 16:31

2 Answers 2

1
Defocus_Array = np.array(('123.3', '0', 'defocus'))
Defocus_Array.astype(float)  # ValueError: could not convert string to float: defocus

Defocus_Array[2] = 'nan'
Defocus_Array.astype(float)  # array([ 123.3,    0. ,    nan])

Or, more generally:

Defocus_Array[Defocus_Array == 'defocus'] = 'nan'
Defocus_Array.astype(float)

Or, if you just want to ignore 'defocus' values:

Defocus_Array[Defocus_Array != 'defocus'].astype(float)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it's exactely what I want!
1

You can write a function, that applies to a whole array like this:

def safe_float(f, default=0):
    try:
        return float(f) 
    except ValueError:
        return default

print z
## ['0' '1' '2' '3' '4' '5' '6' '7' '8' '9' 'foo']
numpy.vectorize(safe_float)(z)
## array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.,  0.])

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.