To convert a 1D array (or a 1D list) to a multidimensional array in Python, you can use the
numpy library. The
numpy library provides functions and classes for working with arrays. You can use the
reshape() function to change the shape of the array and convert it into a multidimensional array. Here’s an example:
import numpy as np array_1d = np.array([1, 2, 3, 4, 5, 6]) num_rows = 2 num_columns = 3 array_2d = np.reshape(array_1d, (num_rows, num_columns)) print(array_2d)
In the code above, we import the
numpy library as
np. We have a 1D array called
array_1d containing elements
[1, 2, 3, 4, 5, 6]. We specify the desired number of rows and columns for the multidimensional array using
We use the
np.reshape() function, passing in the
array_1d and a tuple
(num_rows, num_columns) representing the desired shape of the resulting multidimensional array.
The output will be:
[[1 2 3] [4 5 6]]
In this example, the 1D array
[1, 2, 3, 4, 5, 6] is converted to a 2D array with two rows and three columns. The elements are arranged in row-major order in the resulting multidimensional array.
Note that the total number of elements in the 1D array must match the product of the number of rows and columns in the desired multidimensional array. Otherwise, a
ValueError will occur.