df = df.replace({np.nan: None})

Note: For pandas versions <1.4, this changes the dtype of all affected columns to object.
To avoid that, use this syntax instead:

df = df.replace(np.nan, None)

Note 2: If you don't want to import numpy, np.nan can be replaced with native float('nan'):

df = df.replace({float('nan'): None})

Credit goes to this guy here on this Github issue, Killian Huyghe's comment and Matt's answer.

Answer from EliadL on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › replacing-pandas-or-numpy-nan-with-a-none-to-use-with-mysqldb
Replacing Pandas or Numpy Nan with a None to use with MysqlDB - GeeksforGeeks
July 23, 2025 - import numpy as np temp = np.array([1, np.nan, 3,6,7]) print(arr) temp = np.where(np.isnan(temp), None, temp) print(temp) ... It creates a NumPy array named temp, replaces the np.nan values with None using np.where, and then prints the modified ...
🌐
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 - 33. 34.]] print(np.nan_to_num(a, nan=-1)) # [[11. 12. -1. 14.] # [21. -1. -1. 24.] # [31. 32. 33. 34.]] ... You can use np.nanmean() to replace NaN with the mean of non-NaN values.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.5.dev0 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.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.4 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.
🌐
Statology
statology.org › home › pandas: how to replace nan with none
Pandas: How to Replace NaN with None
December 1, 2022 - You can use the following basic syntax to replace NaN values with None in a pandas DataFrame: ... This function is particularly useful when you need to export a pandas DataFrame to a database that uses None to represent missing values instead of NaN. The following example shows how to use this syntax in practice. ... import pandas as pd import numpy as np #create DataFrame df = pd.DataFrame({'A': [5, 6, 8, np.nan, 4, 15, 13], 'B': [np.nan, 12, np.nan, 10, 23, 6, 4], 'C': [2, 7, 6, 3, 2, 4, np.nan], 'D': [5, np.nan, 6, 15, 1, np.nan, 4]}) #view DataFrame print(df) A B C D 0 5.0 NaN 2.0 5.0 1 6.0 12.0 7.0 NaN 2 8.0 NaN 6.0 6.0 3 NaN 10.0 3.0 15.0 4 4.0 23.0 2.0 1.0 5 15.0 6.0 4.0 NaN 6 13.0 4.0 NaN 4.0
🌐
GitHub
gist.github.com › 4287824
Converting None to NaN in numpy when casting a list to numpy arrays #numpy #c0ldlimit #python · GitHub
I got here while looking for the reverse operation. It can be done like this: u = np.where(np.isnan(y), None, y).tolist()
Find elsewhere
🌐
GitHub
github.com › pandas-dev › pandas › issues › 17494
in consistent result with replace(np.nan, None, inplace=True) · Issue #17494 · pandas-dev/pandas
September 11, 2017 - >>> data = [ ... {'hello': 1, 'mad': 2, 'world': 3}, ... {'mad': 2, 'world': 3}, ... {'world': 1} ... ] >>> df = pd.DataFrame(data) >>> df hello mad world 0 1.0 2.0 3 1 NaN 2.0 3 2 NaN NaN 1 >>> df.hello.dropna() 0 1.0 Name: hello, dtype: float64 >>> import numpy as np >>> df.hello.replace(np.nan, None, inplace=True) >>> df.hello 0 1.0 1 1.0 2 1.0 Name: hello, dtype: float64 >>> Details ·
Author   fsck-mount
🌐
GeeksforGeeks
geeksforgeeks.org › 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
April 25, 2022 - In this article, we will cover how to replace NaN with zero and fill negative infinity values in Python using NumPy. Example Input: [ nan -inf  5.] Output: [0.00000e+00 9.99999e+05 5.00000e+00] Explanation: Replacing NaN with 0 and negative inf with any value.
🌐
Statology
statology.org › home › how to replace nan values with zero in numpy
How to Replace NaN Values with Zero in NumPy
August 28, 2022 - This tutorial explains how to replace NaN values with zero in NumPy, including several examples.
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to replace nan with none in python lists
5 Best Ways to Replace NaN with None in Python Lists - Be on the Right Side of Change
February 16, 2024 - While this method is powerful and efficient for large datasets, it does require the NumPy library, adding an external dependency if not already in use. For those utilizing the Pandas library, which is built on NumPy, the fillna() method is the ...
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-178.php
Python NumPy: Replace all the nan of a given array with the mean of another array - w3resource
August 29, 2025 - # Importing the NumPy library import numpy as np # Creating NumPy arrays: array_nums1 from 0 to 19 reshaped into a 4x5 array and array_nums2 with NaN values array_nums1 = np.arange(20).reshape(4, 5) array_nums2 = np.array([[1, 2, np.nan], [4, 5, 6], [np.nan, 7, np.nan]]) # Printing the original arrays print("Original arrays:") print(array_nums1) print(array_nums2) # Replacing all the NaN values in array_nums2 with the mean of non-NaN values in array_nums1 array_nums2[np.isnan(array_nums2)] = np.nanmean(array_nums1) print("\nAll the NaN of array_nums2 replaced by the mean of array_nums1:") print(array_nums2)
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.

🌐
Arab Psychology
scales.arabpsychology.com › home › how to easily replace nan with none in your pandas dataframe
How To Easily Replace NaN With None In Your Pandas DataFrame
November 22, 2025 - Since NaN is a recognized value within NumPy, we can instruct Pandas to scan the entire DataFrame for every instance of np.nan and substitute it directly with the Python object None.
🌐
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).