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
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Remove NaN (np.nan) from an array | note.nkmk.me
January 23, 2024 - In NumPy, to remove rows or columns containing NaN (np.nan) from an array (ndarray), use np.isnan() to identify NaN and methods like any() or all() to extract rows or columns that do not contain NaN. ...
🌐
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.
Find elsewhere
🌐
NumPy
numpy.org › doc › stable › user › misc.html
Miscellaneous — NumPy v2.5 Manual
Note: cannot use equality to test NaNs. E.g.: >>> myarr = np.array([1., 0., np.nan, 3.]) >>> np.nonzero(myarr == np.nan) (array([], dtype=int64),)
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Replace NaN (np.nan) using np.nan_to_num() and np.isnan() | note.nkmk.me
January 23, 2024 - From NumPy version 1.17, the third argument (nan) allows you to specify the value to replace NaN. a = np.genfromtxt('data/src/sample_nan.csv', delimiter=',') print(a) # [[11. 12. nan 14.] # [21. nan nan 24.] # [31.
🌐
AskPython
askpython.com › python › examples › nan-in-numpy-and-pandas
Understanding np.nan in NumPy and Pandas - AskPython
September 30, 2026 - NumPy promotes this array to float64 because np.nan is a floating-point value and the other entries are integers.
🌐
Interactive Chaos
interactivechaos.com › en › python › function › numpynan
numpy.nan | Interactive Chaos
January 16, 2021 - numpy.nan is a special value from the NumPy library that represents the null value · numpy.nan does not accept arguments
🌐
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 Python, NumPy NAN stands for not a number and is defined as a substitute for declaring value which are numerical values that are missing values in an array as NumPy is used to deal with arrays in Python and this can be initialized using numpy.nan ...
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
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.
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"]})
🌐
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
Learn how to handle NaN values in NumPy arrays by using np.nan_to_num to replace NaNs with a specified number. Perfect for data cleaning and preprocessing 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.
🌐
Reintech
reintech.io › blog › handling-missing-data-nan-values-numpy
Handling Missing Data and NaN Values in NumPy - Reintech
June 13, 2026 - NumPy uses IEEE 754 floating-point special value np.nan to represent missing or undefined numerical data. Unlike None in Python, NaN is a float type that propagates through calculations—any operation involving NaN typically returns NaN.