Table of Contents
Use numpy.array()
Function
To create an array of the arrays in Python:
- Use the
np.array()
function to create anumpy.ndarray
type array of the arrays.
1 2 3 4 5 6 7 8 9 10 |
import numpy as np array1 = np.array([1,2,3]) array2 = np.array([4,5,6]) array3 = np.array([7,8,9]) array = np.array([array1, array2, array3]) print(array) |
1 2 3 4 5 |
[[1 2 3] [4 5 6] [7 8 9]] |
The Python library NumPy scientifically computes advanced numerical work. It is a language extension that adds support for large, multi-dimensional arrays and matrices in the Python language.
The numpy
library provides multi-dimensional array objects that work like arrays in C
but with a Python interface. It can therefore act as a bridge between Python and the low-level languages used for scientific computing.
We used the np.array()
function to create three arrays: array1
, array2
, and array3
. After we finished generating the arrays, we used the np.array()
function to create an arrays of them.
The np.array() function is a general-purpose tool for creating and manipulating arrays in the Python programming language. It converts any iterable object to an array of the same type.
It is not a function in the same sense as len()
or str()
is, but a factory function or class. The constructor can take any number of arguments. For example, we used the np.array()
function to create a numpy.ndarray
type array
of array1
, array2
, and array3
.
Manually create array of arrays
You can directly create array of arrays by specifying array elements to np.array()
method.
Here is an example:
1 2 3 4 5 6 7 |
import numpy as np array = np.array([[1,2,3], [4,5,6], [7,8,9]]) print(array) |
1 2 3 4 5 |
[[1 2 3] [4 5 6] [7 8 9]] |
Here, we directly passed 2d array to np.array()
method to create array of arrays in Python.
Further reading:
Use numpy.append()
Function
To generate an array of the array(s) in Python:
- Use the
np.append()
function that appends arrays to generate anumpy.ndarray
type array.
1 2 3 4 5 6 7 8 9 10 |
import numpy as np array1 = np.array([1,2,3]) array2 = np.array([4,5,6]) array3 = np.array([7,8,9]) array = np.append(arr=[array1], values=[array2, array3], axis=0) print(array) |
1 2 3 4 5 |
[[1 2 3] [4 5 6] [7 8 9]] |
We already discussed the numpy
library and np.array()
function while explaining the code snippet for creating an array of arrays using the numpy.array()
function.
The np.append() is a built-in function in the numpy
library that adds one iterable object to another in Python. It takes arguments as:
- The
arr
to add an iterable at its end. - The
values
to add at the end ofarr
. - The
axis
to append the values along. By default, it flattens thearr
and thevalues
.
We used the np.append()
function to append array2
and array3
to the end of array1
. In addition, we defined axis=0
to make a multi-dimensional array from the arrays instead of flattening them.