How to Create 2-D array using arange() & reshape() functions?

Numpy

Today we are going to learn how to create a 2-D array by using reshape() and arange() functions.

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:

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 argument 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

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]]