You rarely need loops for vector operations in numpy. You can create an uninitialized array and assign to all entries at once:

>>> a = numpy.empty((3,3,))
>>> a[:] = numpy.nan
>>> a
array([[ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN]])

I have timed the alternatives a[:] = numpy.nan here and a.fill(numpy.nan) as posted by Blaenk:

$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a.fill(np.nan)"
10000 loops, best of 3: 54.3 usec per loop
$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a[:] = np.nan" 
10000 loops, best of 3: 88.8 usec per loop

The timings show a preference for ndarray.fill(..) as the faster alternative. OTOH, I like numpy's convenience implementation where you can assign values to whole slices at the time, the code's intention is very clear.

Note that ndarray.fill performs its operation in-place, so numpy.empty((3,3,)).fill(numpy.nan) will instead return None.

Answer from u0b34a0f6ae on Stack Overflow
🌐
Python Guides
pythonguides.com › python-numpy-nan
How NumPy Create NaN Array in Python?
May 16, 2025 - Read ValueError: setting an array element with a sequence error in Python · One of the simplest ways to create a NaN array is by using the np.full() function combined with NumPy’s built-in np.nan constant in Python.
🌐
Java2Blog
java2blog.com › home › python › python array › create array of all nan values in python
Create Array of All NaN Values in Python [5 Ways] - Java2Blog
December 27, 2022 - To create an array of all nan values in Python, use the numpy.full() function to get an array of the specified shape (rows and columns) and fill value.
Discussions

numpy - How to create an array of NA or Null values in Python? - Stack Overflow
This is easy to do in R and I am wondering if it is straight forward in Python and I am just missing something, but how do you create a vector of NaN values and Null values in Python? I am trying ... More on stackoverflow.com
🌐 stackoverflow.com
How should I initialize a numpy array of NaN values?
>>> np.full(3, np.nan) But the bigger question is why would you want to? Edit: as an explanation, your example does not work because you initialized an array of ints. ints have no "NaN" value, only floats do. So your method would work if you initialized an array of floats: >>> x = np.array([0.0,0.0,0.0]) >>> x.fill(np.nan) >>> x array([ nan, nan, nan]) Or converted the ints to floats: >>> x = np.array([0,0,0], dtype=np.float) >>> x.fill(np.nan) >>> x array([ nan, nan, nan]) But the np.full() method is much better. More on reddit.com
🌐 r/learnpython
5
5
April 8, 2016
Setting random NaN in multidimensional numpy array
Good morning to everyone, I am ... 4D numpy array that contains a random number of “nan”. I am following a methodology that I have found in this page (How to randomly insert NaN in a matrix with NumPy in Python ? - GeeksforGeeks), concretely “method 2”, that consists in creating a ... More on discuss.python.org
🌐 discuss.python.org
3
0
July 13, 2022
numpy - What is equivalent of Matlab nan( ) in python? - Stack Overflow
import numpy as np N = 6 nan_array = np.zeros(N) + np.nan More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 3
4

you could use either None or np.nan to create an array of just missing values in Python like so:

np.full(shape=5, fill_value=None)
np.full(shape=5, fill_value=np.nan)

back to your example, this works just fine:

import numpy as np
import pandas as pd

unknowns = np.full(shape=5, fill_value=None)
categories = np.random.choice(['web', 'software', 'hardware', 'biotech'], size = 15, replace = True)
categories = np.concatenate([categories, unknowns])
example = pd.DataFrame(data = {'categories': categories})
example['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']]

print(example['transformed'].value_counts())

Lastly, this line is inefficient. example['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']]

You do want to avoid loops & list comprehensions when using pandas

on large data, this is going to run much faster: example['transformed'] = example.categories.apply(lambda s: s if s else 'unknown')

2 of 3
0

There is a typing problem here.

If you're working in numpy, vectors are typed after being initialized. Assigning a np.nan value to a vector initialized with strings will try to coalesce back into a string:

import numpy as np

v1 = np.array(['a', 'b', 'c'])
v1[0] = np.nan
# v1 = array(['n', 'b', 'c'], dtype='<U1')

v2 = np.array(['ab', 'cd', 'ef'])
v2[0] = np.nan
# v2 = array(['na', 'cd', 'ef'], dtype='<U2')

v3 = np.array(['abc', 'def', 'ghi'])
v3[0] = np.nan
# v3 = array(['nan', 'def', 'ghi'], dtype='<U3')

However, if you're working with pandas in the second half of the question, there's a separate way for handling missing data:

import pandas as pd

df = pd.DataFrame({"x": [pd.NA, "Hello", "World"]})
🌐
Edureka Community
edureka.co › home › community › categories › python › construct an array with nan elements
Construct an array with Nan elements | Edureka Community
July 15, 2019 - I do not know how to construct an array with some Nan elements and other float elements. Can someone share a code for this requirement?
🌐
IncludeHelp
includehelp.com › python › create-numpy-matrix-filled-with-nans.aspx
How to Create NumPy Matrix Filled with NaNs?
May 24, 2023 - You can also create a NumPy matrix filled with NaNs by using the numpy.full() method by specifying the number of rows and columns along with the numpy.NaN.
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › numpy tutorial › numpy nan
NumPy NaN | Working of NumPy NaN in Python with Examples
April 19, 2023 - In NumPy uses nan to assign variables which do not have any values and are needed to be computed. But we should note that in Python NaN is not similar to infinity and we can create NaN values also using float and numpy.nan. Below are the examples of how to create or initialize the array with nan values in Python programs.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Codemia
codemia.io › home › knowledge hub › create numpy matrix filled with nans
Create numpy matrix filled with NaNs | Codemia
September 23, 2025 - Creating a NumPy array filled with NaN is a common way to represent missing values, preallocate partially known tables, or build rolling buffers that are...
🌐
Moonbooks
en.moonbooks.org › Articles › How-to-add-a-new-column-of-nan-values-in-an-array-matrix-with-numpy-in-python-
How to add a new column of nan values in an array (matrix) with numpy in python ?
March 24, 2021 - array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.], [16., 17., 18., 19.]]) new_col = np.empty((A.shape[0],1)) new_col.fill(np.nan) new_col
🌐
w3resource
w3resource.com › python-exercises › numpy › handling-nan-values-in-numpy-arrays-using-np-dot-nan_to_num.php
Handling NaN values in NumPy arrays using np.nan_to_num
Write a NumPy program that creates an array with NaN values and uses np.nan_to_num to replace NaN with a specified number.
🌐
Python.org
discuss.python.org › python help › setting random nan in multidimensional numpy array
Setting random NaN in multidimensional numpy array - Python Help - Discussions on Python.org
July 13, 2022 - Good morning to everyone, I am trying to generate a 4D numpy array that contains a random number of “nan”. I am following a methodology that I have found in this page (How to randomly insert NaN in a matrix with NumPy in Python ? - GeeksforGeeks), concretely “method 2”, that consists in creating a mask.
🌐
Appdividend
appdividend.com › np-nan
Numpy.nan (np.nan) in Python
July 11, 2025 - The numpy.nan (np.nan) is a special floating-point constant defined by the IEEE 754 standard representing a missing or undefined numerical value in an array. It stands for Not a Number (NaN) and has a float type. ... import numpy as np nan_value = np.nan print(nan_value) # Output: nan print(f"Type: {type(nan_value)}") # Output: Type: <class 'float'> print(f"Data type: {np.dtype(type(nan_value))}") # Output: Data type: float64 · Let’s create an array that contains a NaN value.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.full_like.html
numpy.full_like — NumPy v2.5 Manual
January 31, 2021 - Return a new array of given shape filled with value. ... Try it in your browser! >>> import numpy as np >>> x = np.arange(6, dtype=np.int_) >>> np.full_like(x, 1) array([1, 1, 1, 1, 1, 1]) >>> np.full_like(x, 0.1) array([0, 0, 0, 0, 0, 0]) >>> np.full_like(x, 0.1, dtype=np.float64) array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) >>> np.full_like(x, np.nan, dtype=np.float64) array([nan, nan, nan, nan, nan, nan])
🌐
Interactive Chaos
interactivechaos.com › en › python › function › numpynan
numpy.nan | Interactive Chaos
January 16, 2021 - Python scenarios · Full name · ... a value of type float. Examples · We can create a NumPy array that includes null values with the following code: a = np.array([2, np.nan, 4, 1, np.nan]) a ·...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-randomly-insert-nan-in-a-matrix-with-numpy-in-python
How to randomly insert NaN in a matrix with NumPy in Python ? - GeeksforGeeks
July 23, 2025 - Given below are 3 methods to do the same: ravel() function returns contiguous flattened array(1D array with all the input-array elements and with the same type as it). A copy is made only if needed.
🌐
Medium
medium.com › @heyamit10 › understanding-numpy-fillna-equivalent-in-numpy-1caafd79145b
Understanding numpy.fillna Equivalent in NumPy | by Hey Amit | Medium
February 8, 2025 - You might be dealing with datasets in the form of tables or grids (think of Excel sheets or matrices). These are essentially 2D arrays, and NaN can creep into any row or column. But don’t worry! The same tricks—numpy.isnan and numpy.where—can be extended to handle this scenario. Let’s walk through it step-by-step. ... Let’s start by creating a 2D NumPy array that contains some missing (NaN) values.