Coug
Coug

Reputation: 66

Convert an numpy array with header to float

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.

Upvotes: 2

Views: 226

Answers (2)

Frank M
Frank M

Reputation: 1570

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)

Upvotes: 1

Kirill Zaitsev
Kirill Zaitsev

Reputation: 4849

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.])

Upvotes: 1

Related Questions