np.nan has type float: arrays containing it must also have this datatype (or the complex or object datatype) so you may need to cast arr before you try to assign this value.

The error arises because the string value 'nan' can't be converted to an integer type to match arr's type.

>>> arr = arr.astype('float')
>>> arr[arr == 0] = 'nan' # or use np.nan
>>> arr
array([[ nan,   1.,   2.],
       [  3.,   4.,   5.]])
Answer from Alex Riley on Stack Overflow
🌐
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 - When you specify the array (ndarray) as the first argument to np.nan_to_num(), by default, a new ndarray is generated with NaN replaced by 0.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.5 Manual
If x is inexact, NaN is replaced by zero or by the user defined value in nan keyword, infinity is replaced by the largest finite floating point values representable by x.dtype or by the user defined value in posinf keyword and -infinity is replaced by the most negative finite floating point ...
🌐
Statology
statology.org › home › pandas: how to replace zero with nan
Pandas: How to Replace Zero with NaN
October 3, 2022 - import pandas as pd #create DataFrame ... can use the following syntax to replace each zero in the DataFrame with a NaN value: import numpy as np #replace all zeros with NaN values df.replace(0, np.nan, inplace=True) #view updated DataFrame ...
Top answer
1 of 3
3

Randomly replace values in a numpy array

# The dataset
data = pd.read_csv('iris.data')
mat = data.iloc[:,:4].as_matrix()

Set the number of values to replace. For example 20%:

# Edit: changed len(mat) for mat.size
prop = int(mat.size * 0.2)

Randomly choose indices of the numpy array:

i = [random.choice(range(mat.shape[0])) for _ in range(prop)]
j = [random.choice(range(mat.shape[1])) for _ in range(prop)]

Change values with NaN

mat[i,j] = np.NaN

Dropout for any array dimension

Another way to do that with an array of more than 2 dimensions would be to use the numpy.put() function:

import numpy as np
import random
from sklearn import datasets

data = datasets.load_iris()['data']

def dropout(a, percent):
    # create a copy
    mat = a.copy()
    # number of values to replace
    prop = int(mat.size * percent)
    # indices to mask
    mask = random.sample(range(mat.size), prop)
    # replace with NaN
    np.put(mat, mask, [np.NaN]*len(mask))
    return mat

This function returns a modified array:

modified = dropout(data, 0.2)

We can verify that the correct number of values have been modified:

np.sum(np.isnan(modified))/float(data.size)

[out]:

0.2
2 of 3
1

Depending on the data structure you are keeping the values there might be different solutions.

If you are using Numpy arrays, you can employ np.insert method which is referred here:

import numpy as np
a = np.arrray([(122.0, 1.0, -47.0), (123.0, 1.0, -47.0), (125.0, 1.0, -44.0)]))
np.insert(a, 2, np.nan, axis=0)
array([[ 122.,    1.,  -47.],
       [ 123.,    1.,  -47.],
       [  nan,   nan,   nan],
       [ 125.,    1.,  -44.]])

If you are using Pandas you can use instance method replace on the objects of the DataFrames as referred here:

In [106]:
df.replace('N/A',np.NaN)

Out[106]:
    x    y
0  10   12
1  50   11
2  18  NaN
3  32   13
4  47   15
5  20  NaN

In the code above, the first argument can be your arbitrary input which you want to change.

🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.1 Manual
If x is inexact, NaN is replaced by zero or by the user defined value in nan keyword, infinity is replaced by the largest finite floating point values representable by x.dtype or by the user defined value in posinf keyword and -infinity is replaced by the most negative finite floating point ...
Find elsewhere
🌐
Dataquest Community
community.dataquest.io › q&a › dq courses › why should you replace a 0 with a nan value?
Why should you replace a 0 with a NAN value? - DQ Courses - Dataquest Community
January 20, 2021 - Screen Link: My Code: import numpy as np prev_rank_before = f500["previous_rank"].value_counts(dropna=False).head() f500.loc[f500["previous_rank"] == 0, "previous_rank"] = np.nan prev_rank_after = f500["previous_ran…
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.2 Manual
Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the numbers defined by the user using the nan, posinf and/or neginf keywords.
🌐
Moonbooks
en.moonbooks.org › Articles › How-to-replace-nan-value-with-zero-using-numpy-
How to replace nan value with zero using numpy ? - Moonbooks
May 16, 2023 - It also has an optional parameter that can be used to specify the replacement value for nan values instead of using zero, which can be useful in certain situations. To use this function, simply pass in the array containing the nan values as an argument. For example ... array([[ 0.
🌐
AskPython
askpython.com › python-modules › numpy › replacing-nan-infinity-python
Usage of nan_to_num in replacing NaN and Infinity - AskPython
February 23, 2023 - nan_to_num is a function of numpy library that converts NaN (not a number) to a numeric value. The NaN is generally replaced with zero whenever we call upon nan_to_num function.
🌐
NumPy
numpy.org › doc › 2.0 › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.0 Manual
If x is inexact, NaN is replaced by zero or by the user defined value in nan keyword, infinity is replaced by the largest finite floating point values representable by x.dtype or by the user defined value in posinf keyword and -infinity is replaced by the most negative finite floating point ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-numpy-replace-nan-with-zero-and-fill-positive-infinity-for-complex-input-values
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values - GeeksforGeeks
July 23, 2025 - copy: optional value, boolean. ... optional value, int or float.Fill NaN values with this value. NaN values will be substituted with 0.0 if no value is given....
🌐
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 wondering: “Can I use fillna in NumPy like I do in Pandas?” Unfortunately, the answer is no. NumPy doesn’t have a built-in fillna method. But don’t worry—you can achieve the same results using numpy.where or numpy.nan_to_num. For example, if you want to replace NaN values with 0, here’s how you can do it with numpy.nan_to_num:
🌐
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
Define a NumPy array array_with_nan that includes some NaN values. ... Use "np.nan_to_num()" to replace NaN values in the array with a specified number (e.g., 0.0).