Hello everyone. Welcome to a new post on our Python tutorial series, “Learn Python with me”, on our blog. In our previous post, we had a look at the concepts of Python Arrays and numpy package in detail. We will continue the same topic in this post and learn in detail about the dimensions in an array and Python Multi-Dimensional array.
What are Dimensions in Arrays?
The dimensions of an array refer to the way the elements are arranged in an array. It is called a row if the elements are arranged horizontally, and it is called a column if the elements are arranged vertically. We have discussed mainly the single-dimensional arrays so far in our examples. Let us now, however, look at an example on the single-dimensional array for your reference.
#single dimensional array
from numpy import *
array1=array([11,22,33,44,55])
print(array1) #prints array1
array2=array([11,
22,
33,
44,
55])
print(array2) #prints array2
Output
[11 22 33 44 55]
[11 22 33 44 55]
The examples shared above come under the one-dimensional array as they contain only one column or one row. If you create an array with more than one column and one row, it is called a 2-dimensional array. Let us now look at an example to understand the two-dimensional arrays.
#two dimensional array
from numpy import *
array1=array([[11,22,33],
[44,55,66]])
print(array1) #displays the array1
Output
[[11 22 33]
[44 55 66]]
The example shared above is a good one to understand the concept of 2D arrays. You can also notice one thing that the two-dimensional array shared above is, in a way, a combination of several 1D arrays. Similarly, a 3-dimensional array would combine several 2-dimensional arrays, as shared in the example below.
#three dimensional array
from numpy import *
array1=array([[[11, 22], [33, 44]], [[55, 66], [77, 88]]])
print(array1) #displays the array1
Output
[[[11 22]
[33 44]]
[[55 66]
[77 88]]]
Attributes of the array in Python
Let us now learn about the attributes of the array in Python. They are listed below.
- ndim
- shape
- size
- itemsize
- dtype
- nbytes
The ndim attribute
The ndim attribute in Python represents the number of dimensions or axes. You can also refer to it as ‘rank’. For any single dimensional array in python, it returns 1, and for any two-dimensional array, it returns 2. This way, you can quickly determine the array’s dimension in any Python program, as mentioned in the program below.
#ndim attribute program
from numpy import *
array1=array([11,22,33,44,55])
print("Number of dimensions of array1: ",array1.ndim)
array2=array([[11,22,33],
[44,55,66]])
print("Number of dimensions of array2: ",array2.ndim)
Output
Number of dimensions of array1: 1
Number of dimensions of array2: 2
The shape attribute
Just as the name sounds, the shape attribute helps us know the shape of an array in numbers. It is more like a tuple that lists the number of elements in every dimension of the array.
#shape attribute program
from numpy import *
array1=array([11,22,33,44,55])
print("Shape of array1: ",array1.shape)
array2=array([[11,22,33],
[44,55,66]])
print("Shape of array2: ",array2.shape)
Output
Shape of array1: (5,)
Shape of array2: (2, 3)
We can also change the shape of the declared array using the shape attribute. Let us look at an example now.
#change shape of array program
from numpy import *
array1=array([[11,22,33],
[44,55,66]])
print("Array before modifying")
print(array1)
print("Current shape of array1: ",array1.shape)
array1.shape=(3,2)
print("Array after modifying")
print(array1)
print("Current shape of array1: ",array1.shape)
Output
Array before modifying
[[11 22 33]
[44 55 66]]
Current shape of array1: (2, 3)
Array after modifying
[[11 22]
[33 44]
[55 66]]
Current shape of array1: (3, 2)
The size attribute
Just as the name sounds, the size attribute lets us know the number of elements available in the array. For example, please refer to the program below.
#size attribute program
from numpy import *
array1=array([11,22,33,44,55])
print("Size of array1: ",array1.size)
array2=array([[11,22,33],
[44,55,66]])
print("Size of array2: ",array2.size)
Output
Size of array1: 5
Size of array2: 6
The itemsize attribute
The itemsize attribute returns the memory size of the array element in bytes. We all know that 1 byte is equal to 8 bits. To understand more about it, let us look at an example below.
#itemsize attribute program
from numpy import *
array1=array([11,22,33,44,55])
print("Size of array1 in bytes: ",array1.itemsize)
array2=array([[11.1,22.2,33.3],
[44.4,55.5,66.6]])
print("Size of array2 in bytes: ",array2.itemsize)
Output
Size of array1 in bytes: 4
Size of array2 in bytes: 8
The dtype attribute
Using the dtype attribute, you can know the datatype of the elements present in an array. Let us look at an example to understand more about the same.
#dtype attribute program
from numpy import *
array1=array([11,22,33,44,55])
print("Datatype in array1: ",array1.dtype)
array2=array([[11.1,22.2,33.3],
[44.4,55.5,66.6]])
print("Datatype in array2: ",array2.dtype)
Output
Datatype in array1: int32
Datatype in array2: float64
The nbytes attribute
Just as the name sounds, the nbytes attribute lets us know the number of bytes occupied by an array in the python programs. To understand more about the same, let us look at an example now.
total number of bytes = item size of each element in array * size of the array
#nbytes attribute program
from numpy import *
array1=array([11,22,33,44,55])
print("Array1 nbytes: ",array1.nbytes)
array2=array([[11.1,22.2,33.3],
[44.4,55.5,66.6]])
print("Array2 nbytes: ",array2.nbytes)
Output
Array1 nbytes: 20
Array2 nbytes: 48
The reshape() method and flatten() method
Additionally, let us also learn about the reshape() method and flatten() method using which we can perform further changes to Python arrays.
The reshape() method
You can use the reshape() method to change the shape of an array in your python program. Let us look at some examples now.
#reshape method in array program
from numpy import *
array1=array([11,22,33,44,55,66,77,88,99,100])
print("Array1 before modifying: \n",array1)
array1=array1.reshape(2,5)
print("Array1 after modifying: \n",array1)
Output
Array1 before modifying:
[ 11 22 33 44 55 66 77 88 99 100]
Array1 after modifying:
[[ 11 22 33 44 55]
[ 66 77 88 99 100]]
The flatten() method
Using the flatten() method, you can retrieve a copy of the array that’s compressed into one dimension. Let us look at some examples now.
#flatten method in array program
from numpy import *
array1=array([[11,22,33,44,55],[66,77,88,99,100]])
print("Array1 before flattening: \n",array1)
array1=array1.flatten()
print("Array1 after flattening: \n",array1)
Output
Array1 before flattening:
[[ 11 22 33 44 55]
[ 66 77 88 99 100]]
Array1 after flattening:
[ 11 22 33 44 55 66 77 88 99 100]
Dealing with Python Multi-Dimensional arrays
The arrays that have more than one dimension are called Multi-dimensional arrays. For example, the 2d arrays and 3d arrays are considered multi-dimensional arrays. You can also call the 2D array as ‘a x b’ matrix if it has ‘a’ number of rows and ‘b’ number of columns. This concept is taught clearly in mathematics.
Listed below are the number of ways we can create multi-dimensional arrays in Python.
- Using array() function
- Using reshape() function
- Using eye() function
- Using ones() and zeroes() function
Creating multi-dimensional arrays using array() function
You can use the array() function in numpy to construct a multi-dimensional array in Python. In some of the previous examples, we have seen that we generally pass the lists to this array function. If you pass only one list containing elements, it will create a one-dimensional array. If you pass two lists of elements, it will then construct a 2-dimensional array.
#array() function program
from numpy import *
array1=array([11,22,33,44]) #1 dimensional array
print(array1)
print("\t****")
array1=array([[11,22],[33,44]]) #2d array 2 x 2
print(array1)
Output
[11 22 33 44]
****
[[11 22]
[33 44]]
Creating multi-dimensional arrays using reshape() function
We have already discussed the reshape() function in the earlier section of this post. As discussed earlier, it is beneficial in converting a 1-dimensional array to a multi-dimensional array. Please refer to the format below.
reshape(nameofarray,(num,row,column))
In the format shared above, the ‘nameofarray’ refers to the original name of the array in the program. The ‘num’ represents the number of arrays in the new array in the output, which is formed due to reshape() method. The ‘row’ and ‘column’ refer to the respective rows and columns in the same new array.
#creating multi-dimensional using reshape()
from numpy import *
array1=array([11,22,33,44,55,66,77,88,99,100,11,22,33,44,55,66,77,88,99,100])
print("array1 is: ")
print(array1)
print("Let's use reshape() method now")
array2=reshape(array1,(2,2,5))
print("array2 after reshaping: ")
print(array2)
Output
array1 is:
[ 11 22 33 44 55 66 77 88 99 100 11 22 33 44 55 66 77 88
99 100]
Let's use reshape() method now
array2 after reshaping:
[[[ 11 22 33 44 55]
[ 66 77 88 99 100]]
[[ 11 22 33 44 55]
[ 66 77 88 99 100]]]
Creating multi-dimensional arrays using eye() function
Using the eye() function, you can create a two-dimensional array and fill the diagonal elements of the array with 1s and the remaining elements with 0s, as shown in the example below.
#creating multi-dimensional using eye() function
from numpy import *
array1=eye(3)
#format to create using eye() function
#eye(n,dtype=datatype name)
print(array1)
print("One more array")
array1=eye(5,dtype=int)
print(array1)
Output
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
One more array
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]]
Creating multi-dimensional arrays using ones() and zeros() functions in Python
Using the ones() function, you can create a 2-dimensional array with any number of rows and columns as mentioned in the format below.
ones((row,column), dtype)
In the format shared above, ‘row’ represents the number of rows in the array, ‘column’ represents the number of columns in the array. And the ‘dtype’ refers to the datatype of the elements in the array.
#creating multi-dimensional array using ones() function
from numpy import *
array1=ones((2,3),int)
print(array1)
Output
[[1 1 1]
[1 1 1]]
Similarly, as shown in the example below, you can also use the zeros function to create a two-dimensional array with only zeroes.
#creating multi-dimensional array using zeroes() function
from numpy import *
array1=zeros((2,3),int)
print(array1)
Output
[[0 0 0]
[0 0 0]]
How does Indexing work in Python Multi-dimensional arrays?
As discussed in our previous posts, indexing refers to the location number of an element. If you are an avid reader of our blog posts, you know to find the index of each element in a list or a standard array by this time. We can use the same concept in the 2-dimensional arrays with some modifications as mentioned below to deal with the indexing of the multi-dimensional arrays.
p[0][1] #refers to the element in 0th row and 1st column
q[2][3] #refers to the element in 2nd row and 3rd column
Let us now look at an example to retrieve the elements from the 2D array.
#retrieve elements from the 2D array using indexing
from numpy import *
array1=array([[1,2,3],[4,5,6],[7,8,9]])
print("The declared array is: ")
print(array1)
print("Each element in the array is: ")
for i in range(len(array1)):
for j in range(len(array1[i])):
print(array1[i][j],end=' ')
Output
The declared array is:
[[1 2 3]
[4 5 6]
[7 8 9]]
Each element in the array is:
1 2 3 4 5 6 7 8 9
Let us now look into a program in which we can retrieve elements from a 3D array.
#retrieve elements from the 2D array using indexing
from numpy import *
array1=array([[[11,22,33],
[44,55,66]],
[[77,88,99],
[100,111,222]]])
print("The declared array is: ")
print(array1)
print("Each element in the array is: ")
#the logic to display each element
for i in range(len(array1)):
for j in range(len(array1[i])):
for k in range(len(array1[i][j])):
print(array1[i][j][k],end='\t')
print()
print()
Output
The declared array is:
[[[ 11 22 33]
[ 44 55 66]]
[[ 77 88 99]
[100 111 222]]]
Each element in the array is:
11 22 33
44 55 66
77 88 99
100 111 222
How does slicing work in Python Multi-Dimensional arrays?
As mentioned in the previous posts, slicing refers to retrieving a part or a section of an array. We discussed how to perform this operation on single-dimensional arrays. Let us now look at some examples to perform slicing on the multi-dimensional arrays.
Let us look at an example now to understand the slicing on Multi-Dimensional arrays. We’d advise you to practise them line by line on your machine to grasp this concept quickly.
#slicing on multi-dimensional arrays
from numpy import *
array1=array([[11,22,33],[44,55,66],[77,88,99]])
print(array1) #displays the declared array
print("Slicing examples")
print("Displays entire array: \n",array1[:])
print("Displays entire array: \n",array1[: :])
print("Displays entire array: \n",array1[:,:])
print("Displays the 0th row: \n",array1[0,:])
print("Displays the 0th column: \n",array1[:,0])
print("Displays the index 0th row and 0th column: \n",array1[0:1,0:1])
print("Displays the index 1st row and 2nd column: \n",array1[1:2,1:2])
print("Displays the index second row and second column \n",array1[2:3,1:2])
Output
[[11 22 33]
[44 55 66]
[77 88 99]]
Slicing examples
Displays entire array:
[[11 22 33]
[44 55 66]
[77 88 99]]
Displays entire array:
[[11 22 33]
[44 55 66]
[77 88 99]]
Displays entire array:
[[11 22 33]
[44 55 66]
[77 88 99]]
Displays the 0th row:
[11 22 33]
Displays the 0th column:
[11 44 77]
Displays the index 0th row and 0th column:
[[11]]
Displays the index 1st row and 2nd column:
[[55]]
Displays the index second row and second column
[[88]]
Matrices in Numpy
If you were good at mathematics in school, you probably know that the matrices refer to the elements arranged in rows and columns and a rectangular manner. If you have a matrix only with one row, it is called a ‘row matrix’. If you have a matrix only with one column, it is called a ‘column matrix’. As far as the concepts declared in this post are concerned, the row matrix and column matrix can also be considered single-dimensional matrices.
We represent the number of rows and columns of any matrix in ‘a x b’ format. A ‘3 x 4’ matrix means it has three rows and four columns. numpy offers a unique matrix object to work with the matrices using the numpy package in python programs. You can create the numpy matrices using the format mentioned below.
matrix-name=matrix(2D array or string)
The format mentioned above means that the matrix object can receive a 2D array or a string by converting the elements to form a matrix.
#matrix example
from numpy import *
print("Normal matrix: ")
arr=matrix([[1,2,3],[4,5,6]])#declare matrix
print(arr)#display matrix
print("Matrix from string: ")
string1='11 22; 33 44; 55 66' #declare string
string_array=matrix(string1) #convert into matrix
print(string_array) #display the matrix
Output
Normal matrix:
[[1 2 3]
[4 5 6]]
Matrix from string:
[[11 22]
[33 44]
[55 66]]
How to get diagonal elements of any Matrix?
There are inbuilt functions using which you can find only the diagonal elements of any matrix in Python. Please refer to its format below.
p=diagonal(matrix)
Let us look at an example now.
#diagonal retrieval of any matrix
from numpy import *
array1=eye(3,dtype=int)
print("Declared array: \n",array1)
a=diagonal(array1)
print("The diagonal elements are \n",a)
Output
Declared array:
[[1 0 0]
[0 1 0]
[0 0 1]]
The diagonal elements are
[1 1 1]
How to find Average and Sum of elements in matrix?
We can find the average of all the numbers in any matrix using the mean() method and its sum using the sum() method.
#sum and average
from numpy import *
arr=matrix([[1,2,3],[4,5,6]])#declare matrix
print("Declared matrix arr: \n",arr)
print("Average of elements in arr: ",arr.mean())
print("Sum of elements: ",arr.sum())
Output
Declared matrix arr:
[[1 2 3]
[4 5 6]]
Average of elements in arr: 3.5
Sum of elements: 21
How to find Minimum and Maximum elements in a matrix?
We can find any matrix’s minimum and maximum elements using the min() and max() methods, respectively.
#minimum and maximum
from numpy import *
arr=matrix([[1,2,3],[4,5,6]])#declare matrix
print("Declared matrix arr: \n",arr)
print("Minimum element in arr: ",arr.min())
print("Minimum element in arr: ",arr.max())
Output
Declared matrix arr:
[[1 2 3]
[4 5 6]]
Minimum element in arr: 1
Minimum element in arr: 6
How to find the product of elements in a matrix?
We can find the product of the elements in any matrix using the prod() method, as shown in the example below.
#product of elements
from numpy import *
arr=matrix([[1,2,3],[4,5,6]])#declare matrix
print("Declared matrix arr: \n",arr)
print("Product of elements in arr: ",arr.prod())
Output
Declared matrix arr:
[[1 2 3]
[4 5 6]]
Product of elements in arr: 720
How to sort the elements in a matrix?
Using the sort() function in numpy, you can sort the elements in ascending order. Please refer to the format of the sort() function below.
sort(matrixname, axis)
Let us look at an example now.
#sorting of elements in matrix
from numpy import *
arr=matrix([[3,2,1],[6,5,4]])#declare matrix
print("Declared matrix arr: \n",arr)
arr1=sort(arr,axis=1)
print("The sorted matrix: \n",arr1)
Output
Declared matrix arr:
[[3 2 1]
[6 5 4]]
The sorted matrix:
[[1 2 3]
[4 5 6]]
How to find the transpose of a matix?
Converting the rows into columns and the columns into rows are called the ‘Transpose’ of a matrix. We can use the transpose() and getT() methods in numpy to find the transpose of a matrix.
#transpose of matrix program
from numpy import *
arr=matrix([[1,2,3],[4,5,6]])
print("Declared matrix: \n",arr)
arr1=arr.transpose() #transpose using transpose()
print("Transposed matrix: \n",arr1)
arr2=matrix([[3,4,5],[6,7,8]])
print("Declared matrix: \n",arr2)
arr3=arr2.getT() #transpose using getT()
print("Transposed matrix: \n",arr3)
Output
Declared matrix:
[[1 2 3]
[4 5 6]]
Transposed matrix:
[[1 4]
[2 5]
[3 6]]
Declared matrix:
[[3 4 5]
[6 7 8]]
Transposed matrix:
[[3 6]
[4 7]
[5 8]]
How to perform arithmetic operations on matrices?
You can perform arithmetic operations such as division, addition, subtraction, and multiplication on two matrices. Let us look at an example below.
#arithmetic operations on matrices
from numpy import *
arr1=matrix([[1,2,3],[4,5,6]])
arr2=matrix([[4,5,6],[1,2,3]])
print("The arr1 matrix is: \n",arr1)
print("The arr2 matrix is: \n",arr2)
print("arr1 + arr2 = \n",arr1+arr2)
print("arr1 - arr2 = \n",arr1-arr2)
print("arr1 * arr2 = \n",arr1*transpose(arr2))
print("arr1 / arr2 = \n",arr1/arr2)
Output
The arr1 matrix is:
[[1 2 3]
[4 5 6]]
The arr2 matrix is:
[[4 5 6]
[1 2 3]]
arr1 + arr2 =
[[5 7 9]
[5 7 9]]
arr1 - arr2 =
[[-3 -3 -3]
[ 3 3 3]]
arr1 * arr2 =
[[32 14]
[77 32]]
arr1 / arr2 =
[[0.25 0.4 0.5 ]
[4. 2.5 2. ]]
Random Numbers
A random number is something that’s generated out of our control. When you develop a random number, you would not know which number the code will generate for you. Using the rand() function on the random module of the numpy package, you can achieve the same.
Let us look at a program to understand the concept of random numbers.
#random numbers on Python
from numpy import *
arr=random.rand(3,3)
print(arr)
Output
[[0.13449692 0.42235592 0.72314512]
[0.44397973 0.10869844 0.23534308]
[0.02647632 0.4791612 0.6183889 ]]
You can see in the program above that it generated a matrix with three rows and three columns with random numbers as expected.
We hope you have liked this post and for more similar posts on the Python programming language, stay tuned with our blog.