0

Assume that I have the following list:

import numpy as np

a = [[1,    1.1, 'a'],
     ['ab', '1', '1.1']]
a_np = np.array(a)
print(a_np)

>>> [['1' '1.1' 'a']
    ['ab' '1' '1.1']]

I would like to turn a_np into an array of np.float64 values. However...

print(np.float64(a_np))
>>> ValueError: could not convert string to float: 'a'

...some of these values are not able to be turned into floats.

Is there a pythonic way to turn the array into an array of floats while turning the rest of the values into np.nan objects?

Desired:

print(pythonic_float_function(a_np))
>>> [[ 1.   1.1  nan]
    [ nan  1.   1.1]]
3
  • stackoverflow.com/questions/16223483/… Commented Aug 1, 2017 at 0:29
  • If you use pandas, pd.to_numeric(..., errors='coerce') works well. Commented Aug 1, 2017 at 0:43
  • pd.to_numeric(a_np.reshape(-1, ), errors='coerce').reshape(a_np.shape) Commented Aug 1, 2017 at 0:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.