Like other programming languages, Python also contains several built-in data structures, for instance, arrays. Arrays can be one-dimensional, two-dimensional, or depending on the user’s requirements, provide a way to organize and save data. Additionally, you can use the built-in Python methods to retrieve or modify that data.
This post will illustrate the different methods for converting a 1d array into a 2d array.
How to Convert 1d Array to 2d Array in Python?
To perform the converting operation on a one-dimensional array to a two-dimensional array in Python, the “reshape()” function can be utilized that enables users to reshape an array. More specifically, reshaping is known as changing the shape of a given array which is determined by the number of elements in every dimension without changing its data.
Utilize the below-stated syntax for the reshape() method:
Here, the “input_string” is the variable name that contains the value of the array, the “row” and “col” are two parameters that are passed to the “reshape” function.
Example 1: Convert 1d Array to 2d Array in Python Using “reshape()” Method With “np.arange()” Method
To convert a one-dimension array to a two-dimensional array, first import the Numpy library as np:
Now, create an array variable and initialize it with the term “original_array”. Then, assign a value by utilizing an “np.arange()” function:
Here, “arange()” is the function of the “np” library, and we have passed a value “8” as the function parameter.
Print the previously created array using the “print()” function:
Next, create a variable that will keep the converted array. Then, call the “reshape()” method by passing a desired number of rows and columns as an argument to associate this method with the specified variable:
Finally, print the converted array:
It can be seen that the specified one-dimensional array has been successfully converted to a two-dimensional array:
Example 2: Convert 1d Array to 2d Array in Python Using “np.reshape()” Method
Another way to convert the 1d array into the 2d array is to utilize the “np.reshape()” function. To do so, first, create a new 1d input array:
Then, print the 1d array:
Now, call the “np.reshape()” method with a 1d input array by passing the parameters. Here, the “-1” refers to the size of the specified input array:
Print the resultant 2d array from the np.reshape() method:
That’s all about converting a 1d array into a 2d array in Python through different methods.
To convert a 1d array into a 2d array in Python, the “np.reshape()” method and “reshape()” method with the “np.arange()” method can be used. Both methods enable users to reshape the input array without modifying its data. This post illustrated the different methods for converting a 1d array into a 2d array.