How to Create an Array of Arrays in Python (With Examples)


You can use one of the following two methods to create an array of arrays in Python using the NumPy package:

Method 1: Combine Individual Arrays

import numpy as np

array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
array3 = np.array([7, 8, 9])

all_arrays = np.array([array1, array2, array3])

Method 2: Create Array of Arrays Directly

import numpy as np

all_arrays = np.array([[1, 2, 3],
                       [4, 5, 6],
                       [7, 8, 9]])

The following examples show how to use each method in practice.

Method 1: Combine Individual Arrays

The following code shows how to create an array of arrays by simply combining individual arrays:

import numpy as np

#define individual arrays
array1 = np.array([10, 20, 30, 40, 50])
array2 = np.array([60, 70, 80, 90, 100])
array3 = np.array([110, 120, 130, 140, 150])

#combine individual arrays into one array of arrays
all_arrays = np.array([array1, array2, array3])

#view array of arrays
print(all_arrays)

[[ 10  20  30  40  50]
 [ 60  70  80  90 100]
 [110 120 130 140 150]]

Method 2: Create Array of Arrays Directly

The following code shows how to create an array of arrays directly:

import numpy as np

#create array of arrays
all_arrays = np.array([[10, 20, 30, 40, 50],
                       [60, 70, 80, 90, 100],
                       [110, 120, 130, 140, 150]])

#view array of arrays
print(all_arrays)

[[ 10  20  30  40  50]
 [ 60  70  80  90 100]
 [110 120 130 140 150]]

Notice that this array of arrays matches the one created using the previous method.

How to Access Elements in an Array of Arrays

You can use the shape function to retrieve the dimensions of an array of arrays:

print(all_arrays.shape)

(3, 5)

This tells us that there are three rows and five columns in the array of arrays.

You can use the size function to see how many total values are in the array of arrays:

print(all_arrays.size)

15

This tells us that there are 15 total values in the array of arrays.

You can use brackets to access elements in certain positions of the array of arrays.

For example, you can use the following syntax to retrieve the value in the first array located in index position 3:

print(all_arrays[0, 3])

40

We can use this syntax to access any value we’d like in the array of arrays.

Additional Resources

The following tutorials explain how to perform other common operations with arrays in Python:

How to Concatenate Arrays in Python
How to Create Pandas DataFrame from NumPy Array
How to Convert Pandas DataFrame to NumPy Array

Leave a Reply

Your email address will not be published. Required fields are marked *