1

I have a float64 numpy array that contains values and also NaN's:

[[ 5. nan nan nan nan nan nan nan nan nan nan nan nan]
 [nan  6. nan nan nan nan nan nan nan nan nan nan nan]
 [nan  7.  5. nan nan nan nan nan nan nan nan nan nan]
 [nan nan nan  7. nan nan nan nan nan nan nan nan nan]
 [nan nan nan nan  4. nan nan nan nan nan nan nan nan]
 [nan nan nan nan  5.  3. nan nan nan nan nan nan nan]
 [nan nan nan nan nan nan nan nan nan nan nan nan nan]
 [ 1. nan nan nan nan nan nan  4. nan nan nan nan nan]
 [nan nan nan nan nan nan  7. nan nan nan nan nan nan]
 [nan nan nan nan nan nan nan nan nan  7. nan nan nan]
 [nan nan nan nan nan nan  7. nan  7. nan  6. nan nan]
 [nan nan nan nan nan nan nan nan nan nan nan  7. nan]
 [nan nan nan nan nan nan nan  6. nan nan nan nan  5.]]

I want to convert all the numbers to integers but np.round or np.around does not quiet seems to do the job. Also, I am unable to change the type of the array because integer type arrays do not support "nan's". How do I do this?

4
  • What's the array dtype supposed to be? Commented Dec 9, 2018 at 22:49
  • numpy.nan_to_num(arr, copy=False), works on arrays. What value do you want nan replaced with? Commented Dec 9, 2018 at 23:01
  • np.round doesn't change the dtype. Commented Dec 9, 2018 at 23:45
  • What value do you want NaN replaced with? Zero, or some other specific value? Commented Dec 10, 2018 at 0:31

2 Answers 2

3

To convert NaN to zero: numpy.nan_to_num(arr), works directly on arrays, as well as single values. (Use the ..., copy=False arg to avoid wasting memory, i.e. operate in-place.)

So to do both the NaN replacement then type-conversion: numpy.nan_to_num(arr).astype(np.int)

from numpy import array, nan
arr = np.array([[5., nan, nan], [nan, 6., nan], [nan, 7., 5.]])

arr = np.nan_to_num(arr, copy=False).astype(np.int)
array([[5, 0, 0],
       [0, 6, 0],
       [0, 7, 5]])

To convert NaN to any other specific value: You didn't say what value you want to replace NaN with. If you want a different replacement value than zero, you'll need to do that using logical indexing: arr[np.isnan(arr)] = -99 then .astype(np.int).

Sign up to request clarification or add additional context in comments.

Comments

2

The question is, to what value should these be converted to?

Let's say this array is names x, then:

x[np.isnan(x)] = 0 # value you want to replace NaN with

And now, you can convert your data to integers the way you wanted to.

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.