14

I'm trying to pad an array with np.nan

import numpy as np
print np.version.version
# 1.10.2
combine = lambda real, theo: np.vstack((theo, np.pad(real, (0, theo.shape[0] - real.shape[0]), 'constant', constant_values=np.nan)))
real = np.arange(20)
theoretical = np.linspace(0, 20, 100)
result = combine(real, theoretical)
np.any(np.isnan(result))
# False

Inspecting result, it seems instead of np.nan, the array is getting padded with -9.22337204e+18. What's going on here? How can I get np.nan?

4
  • 2
    Try real = np.arange(20, dtype=float). Commented Feb 19, 2016 at 21:10
  • 2
    Look at the result produced by np.pad(real, (0, theo.shape[0] - real.shape[0]), 'constant', constant_values=np.nan) when real is an integer array. Commented Feb 19, 2016 at 21:12
  • Thanks - forgot real was an integer array. Why does this behaviour happen with integers? Commented Feb 19, 2016 at 21:27
  • np.nan is a float. Commented Feb 19, 2016 at 21:29

1 Answer 1

13

The result of pad has the same type as the input. np.nan is a float

In [874]: np.pad(np.ones(2,dtype=int),1,mode='constant',constant_values=(np.nan,))
Out[874]: array([-2147483648,           1,           1, -2147483648])

In [875]: np.pad(np.ones(2,dtype=float),1,mode='constant',constant_values=(np.nan,))
Out[875]: array([ nan,   1.,   1.,  nan])

The int pad is np.nan cast as an integer:

In [878]: np.array(np.nan).astype(int)
Out[878]: array(-2147483648)
Sign up to request clarification or add additional context in comments.

2 Comments

Is there an integer version of np.nan?
Masked arrays use 999999 as the default fill_value, but values like that don't propagate through calculations in the same way that np.nan does. Talk about nan often references IEEE-754 floating point standard.

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.