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
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ create-numpy-matrix-filled-with-nans.aspx
How to Create NumPy Matrix Filled with NaNs?
May 24, 2023 - In this way, to create a NumPy matrix filled with NaNs, you can simply create an empty matrix by using the numpy.empty() method by passing the number of rows and columns and then fill the NaN values using the numpy.fill() method.
๐ŸŒ
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
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
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. ...
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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
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"]})
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ test-array-values-for-nan-in-numpy
Test array values for NaN in Numpy
February 8, 2022 - import numpy as np # Create an ... in the Array print("\nNumber of elements...<br>", arr.size) # To test array for NaN, use the numpy.isnan() method in Python Numpy print("\nTest array for NaN...<br>",np.isnan(arr...
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
YouTube
youtube.com โ€บ finxter
How to Create a NumPy Array and Fill It With NaN Values? - YouTube
Full Tutorial: https://blog.finxter.com/how-to-create-a-numpy-array-and-fill-it-with-nan-values/Email Academy: https://blog.finxter.com/email-academy/โ–บโ–บ Do y...
Published: January 26, 2022
Views: 370