Convert a 1D array to a 2D Numpy array

Convert a 1D array to a 2D Numpy array

To convert a 1D array to a 2D numpy array, you can use the reshape() function provided by numpy. The reshape() function allows you to specify the new shape that you want.

Here's how you can do it:

  • Given a 1D array:
import numpy as np # Create a 1D numpy array arr = np.array([1, 2, 3, 4, 5, 6]) print(arr) 
  • Convert to 2D array:

You can reshape this 1D array into a 2D array with 2 rows x 3 columns:

arr_2d = arr.reshape(2, 3) print(arr_2d) 

Output:

[[1 2 3] [4 5 6]] 

Or reshape it into a 3 rows x 2 columns 2D array:

arr_2d = arr.reshape(3, 2) print(arr_2d) 

Output:

[[1 2] [3 4] [5 6]] 

Remember that the product of the new shape's dimensions (rows x columns) must equal the total number of elements in the original 1D array. If they don't match, you'll get a ValueError.


More Tags

strcat propertygrid rabbitmq-exchange android-overlay byte class-method server-side-rendering asp.net-core-2.1 python-3.3 formsy-material-ui

More Programming Guides

Other Guides

More Programming Examples