In this blog, we will begin our discussion of NumPy libraries of Python and will understand various operations with single-dimensional arrays.
Let’s first understand array attributes by taking examples of one-dimensional, two-dimensional and three-dimensional arrays.
Using NumPy’s random number generator, we have seeded a set value to ensure the generation of the same random arrays on every successful execution of the code.
Using the below code, we have created 1D, 2D, and 3D arrays by passing the maximum element and the size of the array as the two parameters in the numpy.random.randint function.
import numpy as np np.random.seed(0) A1= np.random.randint(8,size = 6) A2 = np.random.randint(8,size = (3,4)) A3 = np.random.randint(8,size = (3,4,5))
Finding the number of dimensions, the size of each dimension and the total size of the array
We have used attributes like ndim, shape, and size to find the all the values of all the above parameters.
Understanding Data Types in Python using dtype attribute.
Indexing in NumPy is similar to indexing in Python as in any one-dimensional array
Using Negative Indices
The code below demonstrates how to perform indexing from the end.
From the array A1, we have retrieved the last element using the index value as -1 and 4th value i.e. 5 from last using index value as -4. Similarly, we have done this for the A3 array also.
Accessing Elements In The Multi-Dimensional Array
Using the code below, we have accessed the items from multi-dimensional array A2 with a comma-separated tuple of indices.
Modification Of The Values Of Array
Values can be modified using the below index notation.
We have modified the second element of the first row and have changed it from 7 to 12.
Working With One-Dimensional Sub-Arrays
We have stored 10 integers in array A using arange function. We will be doing various operations on the same array in the subsequent sections.
Accessing the first 5 elements
Operations On The Middle Sub-Array
Accessing the 4th,5th and 6th element
Accessing the 5th,6th and 7th element
Accessing every other element
Accessing every 2nd element
Accessing every 4th element
Reversing an Array
Reversing an array with the step value of 2
Reversing every element from the 5th index with step value 2
Reversing every element from the 8th index with step value 3
This sums up our discussion on the first part of NumPy.
In the next article of the NumPy series, we will discuss more operations on multi-dimensional arrays.