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 - Let’s look at a practical example where NaN arrays are essential. Imagine we’re analyzing stock market data for the top 5 tech companies, but we’re missing data for some days: import numpy as np import pandas as pd import matplotlib.pyplot as plt # Stock tickers for top tech companies tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META'] # Create a 5x7 array for a week of stock prices (with missing data) stock_data = np.full((5, 7), np.nan) # Fill in some known values (simulated data) stock_data[0, :5] = [150.2, 151.3, 149.8, 152.0, 153.5] # AAPL (missing weekend) stock_data[1, :] = [290.1
Discussions

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
numpy - How to create an array of NA or Null values in Python? - Stack Overflow
There are data typing issues here. You can create an array of np.nan, but that's a floating point value. You can create an array of empty strings, if that solves the problem. You can't put None in a string array. All elements in a numpy array must be the same type. More on stackoverflow.com
🌐 stackoverflow.com
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
Creating an array who size and values depend on another array's values being put through a function
Since you mention arrays and arange, I presume you're using Numpy. The way to create one array by applying a function to each element from another array is by using vectorize . More on reddit.com
🌐 r/learnpython
6
18
May 21, 2022
🌐
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.
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"]})
🌐
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.
🌐
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 empty until measurements arrive.
Find elsewhere
🌐
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?
🌐
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 - 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. Syntax : ... Choose random indices to Nan value to.
🌐
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 - Let's first create an array with numpy · import numpy as np A = np.arange(20) A = A.reshape(5,4) A = A.astype('float64') returns · 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.
🌐
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 the above program, we can see we have firstly imported the NumPy module, then we are using the alias name of NumPy to initialize nan value in the array items when creating an array using NumPy.array() function.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Interactive Chaos
interactivechaos.com › en › python › function › numpynan
numpy.nan | Interactive Chaos
January 16, 2021 - 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 · array([2., nan, 4., 1., nan]) Note that the result is an array of type float, as it includes both integer and real values (the null values): a.dtype ·
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.5 Manual
>>> import numpy as np >>> np.nan_to_num(np.inf) 1.7976931348623157e+308 >>> np.nan_to_num(-np.inf) -1.7976931348623157e+308 >>> np.nan_to_num(np.nan) 0.0 >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333) array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03, -1.2800000e+02, 1.2800000e+02]) >>> nan = np.array([11, 12, -9999, 13, 14]) >>> posinf = np.array([33333333, 11, 12, 13, 14]) >>> neginf = np.
🌐
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.
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.1 Manual
>>> import numpy as np >>> np.nan_to_num(np.inf) 1.7976931348623157e+308 >>> np.nan_to_num(-np.inf) -1.7976931348623157e+308 >>> np.nan_to_num(np.nan) 0.0 >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333) array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03, -1.2800000e+02, 1.2800000e+02]) >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)]) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(y) array([ 1.79769313e+308 +0.00000000e+000j, # may vary 0.00000000e+000 +0.00000000e+000j, 0.00000000e+000 +1.79769313e+308j]) >>> np.nan_to_num(y, nan=111111, posinf=222222) array([222222.+111111.j, 111111.