1

I was working on this piece of code and was stuck here.

import numpy as np
a = np.arange(10)
a[7:] = np.nan

By theory, it should insert missing values starting from index 7 until the end of the array. However, when I ran the code, some random values are inserted into the array instead of NA's.

Can someone explain what happened here and how should I insert missing values intentionally into numpy arrays?

jpp
  • 159,742
  • 34
  • 281
  • 339
vivek
  • 563
  • 7
  • 16
  • 1
    `how should I insert missing values intentionally into numpy arrays` - Change dtype to float. – Divakar Jul 31 '18 at 11:14
  • Possible duplicate of [Numpy integer nan](https://stackoverflow.com/questions/12708807/numpy-integer-nan) – jpp Jul 31 '18 at 11:16

1 Answers1

1

Not-a-number (NA) is a special type of floating point number. By default, np.arange() creates an array of type int. Casting this to float should allow you to add NA's:

import numpy as np
a = np.arange(10).astype(float)
a[7:] = np.nan
Marijn van Vliet
  • 5,239
  • 2
  • 33
  • 45