How to Create 2D numpy array using arange & reshape

Today we are going to learn how to create 2D numpy array using arange & reshape. First, we will create a linear 1-D array by using arange() function and then we will convert it to 2-D array.So let us begin with our example:

1. Using arrange() function


We will use arange() function to create a linear array of 8 values.

#Example

import numpy as np
array_three = np.arange(8)
print("Array using arange",array_three)

Output

Array using arange [0 1 2 3 4 5 6 7]

We got the linear 1-D array and now we can use reshape() function to reshape this array into 4×2 array.

An important point to note here is that arguments in reshape should be equal to arrange arguments when they are multiplied.For Example in our example we are passing 8 in arange() so in reshape, we can pass 4,2 or 2,4 or 2,2,2

2. Using numpy.reshape() function


Example

import numpy as np
array_three = np.arange(8).reshape(4,2) 
print("2D Array using reshape and arange",array_three)

output

2D Array using reshape and arange [[0 1]
 [2 3]
 [4 5]
 [6 7]]