How to Fix ValueError: ‘Object arrays cannot be loaded when allow_pickle=False’

Python raises ValueError: ‘Object arrays cannot be loaded when allow_pickle=False’ when you try to load a NumPy file (.npy) containing object arrays, but the ‘allow_pickle’ parameter is set to False. By default, this parameter is set to False for security reasons, as loading pickled object arrays can lead to arbitrary code execution.

There are two ways to fix the ValueError: ‘Object arrays cannot be loaded when allow_pickle=False’ error.

Method 1: Set ‘allow_pickle=True’

You can Set ‘allow_pickle=True’ when loading the NumPy file. Remember that this could expose you to potential security risks if the file is from an untrusted source.

import numpy as np

data = np.load('file.npy', allow_pickle=True)

Method 2: Save your data as a non-object array

If possible, save your data as a non-object array, such as a numerical or boolean array, which can be loaded without pickling. This is the preferred solution if you have control over the file format.

For example, you can convert a list of lists into a 2D NumPy array:

import numpy as np

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
array_2d = np.array(list_of_lists, dtype=int)

np.save('file.npy', array_2d)

Then, you can load the file without having to set ‘allow_pickle=True’:

import numpy as np

data = np.load('file.npy')

If neither of these solutions is applicable, you might want to consider alternative file formats like JSON, CSV, or HDF5, which are better suited for storing mixed data types.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.