Examples of Generating 2-D Numpy Array

This tutorial provides 3 methods to create 2-D Numpy Arrays in Python. The following is the key syntax for these 3 methods. After that, 3 Python Numpy code examples are provided.

Method 1:

np.array[[numbers in the first row ], [numbers in the second row]]

Method 2:

np.zeros(shape(row number, column number))

Method 3:

array_name=np.arange(length number)
array_name=array_name.reshape(row number, column number)

Example 1: Create a 2-D array

# import numpy 
import numpy as np

# create 2-D array_a
array_a=np.array([[1,2,4],[2,1,5]])

# print out array_a
print("array_a:\n",array_a)

# check the shape of array_a
print("the dimension of array_a:\n", array_a.shape)

Output:

array_a:
 [[1 2 4]
 [2 1 5]]

the dimension of array_a:
 (2, 3)

Example 2: Create 2-D arrays of all zero

# import numpy 
import numpy as np

# create a 2-D all zero array
array_zero=np.zeros(shape=(4, 2))

# print out the array_zero
print(array_zero)

Output:

[[0. 0.]
 [0. 0.]
 [0. 0.]
 [0. 0.]]

Example 3: Create sequential numbers 2-D array

The following is to generate a array with sequential numbers. It has two components, one is before reshaping, and it is 1 dimension. After reshaping, it becomes 2 dimensions.

# import numpy 
import numpy as np

# create a range of 10, namely numbers from 0 to 9
array_c=np.arange(10)

# print out array_c
print("array_c:\n",array_c)
print("checking type of array_c:\n",type(array_c))
print("checking shape of array_c:\n", np.shape(array_c))
print("checking the dimension of array c:\n", array_c.ndim)

# reshape it
array_c=array_c.reshape(2,5) 

# print out array_c
print("reshaped array_c:\n", array_c)
print("checking shape of reshaped array_c:\n", np.shape(array_c))
print("checking the dimension of reshaped array_c:\n", array_c.ndim)

Output:

array_c:
 [0 1 2 3 4 5 6 7 8 9]

checking type of array_c:
 <class 'numpy.ndarray'>

checking shape of array_c:
 (10,)

checking the dimension of array c:
 1

reshaped array_c:
 [[0 1 2 3 4]
 [5 6 7 8 9]]

checking shape of reshaped array_c:
 (2, 5)

checking the dimension of reshaped array_c:
 2

Further Reading