Explain Codes LogoExplain Codes Logo

Convert NumPy array to Python list

python
list
numpy
dataframe
Anton ShumikhinbyAnton Shumikhin·Sep 26, 2024
TLDR

Transform a NumPy array into a Python list with .tolist():

import numpy as np numpy_array = np.array([1, 2, 3]) print(numpy_array.tolist()) # Outputs: [1, 2, 3]

For multi-dimensional arrays, the tolist() function will create a nested list:

import numpy as np numpy_array_2d = np.array([[1, 2, 3], [4, 5, 6]]) print(numpy_array_2d.tolist()) # Outputs: [[1, 2, 3], [4, 5, 6]]

List() and NumPy data types

Deviate to the list() function if you want to preserve the NumPy scalar types. It keeps the NumPy types intact in the resulting list:

import numpy as np numpy_array = np.array([np.int32(1), np.float32(2), np.complex64(3+2j)]) # Here list is the Dumbledore of Python, preserving original forms! python_list = list(numpy_array) print(python_list) # Outputs: [numpy.int32(1), numpy.float32(2), numpy.complex64(3+2j)]

Exploring dimensions and shapes

Knowing the dimensions and shape of your array before converting is quite beneficial. Think of a multi-dimensional array conversion yielding a nested list resembling the shape of a Matrix inception.

Ensure data integrity

Confirm that your data transfer is exact. Double-check your NumPy array's dimensions and shape before converting:

import numpy as np numpy_array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) print(f"Shape before conversion, almost like a pre-flight check: {numpy_array_3d.shape}") converted_list = numpy_array_3d.tolist() print(f"Depth of the converted list, did we get everything out?: {len(converted_list)}")

Flat layout methods

If you want to flatten your multi-level concert (array) before booing them off (conversion), you can call the ndarray.flatten() or np.ravel() methods:

import numpy as np numpy_array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # Using flatten() The 'I am bored, let's speed things up!' way flat_list = numpy_array_3d.flatten().tolist() print(flat_list) # Outputs: [1, 2, 3, 4, 5, 6, 7, 8] # Also, np.ravel() works too. A fearless rival of flatten() flat_list_ravel = np.ravel(numpy_array_3d).tolist() print(flat_list_ravel) # Should give the same result

More ways to Rome than one (tolist())

When .tolist() feels like a great friend but not enough to marry, alternate methods have your back.

Flattening: The B-plan

For a times when flattening needs itertools.chain.from_iterable for those 'I forgot to use NumPy' kind of days:

import numpy as np import itertools numpy_array_2d = np.array([[1, 2], [3, 4]]) # Bored with flatten()? Here's something different flat_list_Bplan = list(itertools.chain.from_iterable(numpy_array_2d)) print(flat_list_Bplan) # Outputs: [1, 2, 3, 4]

Reconversion

Had a change of heart? Turn it back into a NumPy array with np.asarray():

import numpy as np python_list = [1, 2, 3, 4] # Python list was fun but let's go back to NumPy array numpy_array = np.asarray(python_list) print(numpy_array) # Outputs: [1, 2, 3, 4]

Shapes matter

Not happy with your array's personality (shape)? Change it:

import numpy as np # Makeover time. Alter your array's shape as required numpy_array = np.arange(6).reshape(2, 3) print(numpy_array.tolist()) # Outputs: [[0, 1, 2], [3, 4, 5]]

Say Hello to comprehensions

For times when flattening arrays is cool, but not with pandas DataFrames:

import numpy as np import pandas as pd df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]])) # The not-so-basic way of flattening list_flattened = [element for sublist in df.values for element in sublist] print(list_flattened) # Outputs: [1, 2, 3, 4, 5, 6]

Post-conversion verification steps

Always run a quick health check of type, size, and shape post-conversion:

import numpy as np numpy_array = np.array([[1, 2], [3, 4]]) converted_list = numpy_array.tolist() print(f"Type before: {type(numpy_array)}, Size before: {numpy_array.shape}") print(f"Type after: {type(converted_list)}, Size after: {len(converted_list)}")