A handbook of NumPy basic operations with python
NumPy is a python library package used for multidimensional array computing. NumPy process is faster than list because of its homogeneous type that is packed densely in memory and performed vectorization. Vectorization means the computation done with parallel hardware process to make it fast. NumPy is the main purpose so, it is used in various fields like statistics, algebra, matrix operations, etc. The types of arrays we work with are shown below:
Introduction and Basic of array
A class named array is used in NumPy for more functionality with its attributes. The different attributes in this functionality are dimensions, shape, size, type, etc. Let’s take the example to know about these attributes.
#First need to import the library to use NumPy
import numpy as np# 2-D array
a = np.arange(9).reshape(3,3)
We created a 2-D array with having 2 axes. The view of the matrix formed with this operation is print. The matrix formed is 3 rows and 3 columns.
print(a)#output:
array([[0,1,2],
[3,4,5],
[6,7,8]])
The functionality of attributes related to these arrays are shown below:
#to know the shape of the array
a.shape #output:(3, 3)#to know the dimension(axes) of the array
a.ndim #output:2#to know the type of the array elements
a.dtype.name #output:'int64'#to know the item size of the array
a.itemsize #output:8#to know the size of the array
a.size #output:9#to know the type of the array
type(a) #output:<class 'numpy.ndarray'>
In this article, we will cover the most basic fundamentals use in daily life programming. First, we need to install NumPy if there is no anaconda distribution.
#to install NumPy
pip install numpy
Every time when we want to use NumPy, we have to import it as we see in the previous example.
An array is a structure that contains information in a grid format, and each position in the grid is called an element. Whenever we want to extract information from the grid, we have to specify the position of element/s.
There is a number of ways we can create arrays in python. The most common way is by np.array function. Let us see other ways too.
##importing library
import numpy as np##creating array with np.array
array1 = np.array([3, 5, 9])#output: array([3, 5, 9])##creating array will all element values are zeros
array2 = np.zeros(3) # all three elements will have zero value#output: array([0., 0., 0.])##creating array with np.ones
array3 = np.array(3) # all three elements will have one value#output: array([1., 1., 1.])##creating array with np.arange
array4 = np.arange(3) # values begin with 0 and goes till the
number of elements#output: array([0, 1, 2])##arange is also used to create array with evenly distributed
array5 = np.arange(3, 13, 3) #last 3 is a step size#output: array([3, 6, 9, 12])
Adding and Sorting of array
Sorting means arranging the values in ascending order.
array1 = np.array([3, 8, 2, 6, 1, 9])
sorted_array = np.sort(array1)#output: array([1, 2, 3, 6, 8, 9])
Adding means concatenate two arrays.
array1 = np.array([3, 5, 8])
array2 = np.array([4, 6, 9])array3 = np.concatenate((array1, array2))#output: array([3, 5, 8, 4, 6, 9])
Reshape Function
We can reshape the array in suitable rows and columns.
array1 = np.arange(6)
array2 = array1.reshape(3, 2) # 3 rows and 2 columns#output: array([[0, 1],
[2, 3],
[4, 5]])
Indexing and Slicing
Indexing and slicing are used when we want information from the middle of the data.
array1 = np.array([3, 5, 2, 8, 4])array1[2]#output: 2array1[0:3]#output: array([3, 5, 2])array1[3:]#output: array([8, 4])
Operations on array
- Stacking arrays vertically
array1 = np.array([[3, 5],
[2, 1]])
array2 = np.array([[4, 6],
[8, 7]])np.vstack((array1, array2))#output: array([[3, 5],
[2, 1],
[4, 6],
[8, 7]])
- Stacking arrays horizontally
array1 = np.array([[3, 5],
[2, 1]])
array2 = np.array([[4, 6],
[8, 7]])np.hstack((array1, array2))#output: array([[3, 5, 2, 1],
[4, 6, 8, 7]])
It is used to copy an array to save as original for later use with operations.
array1 = np.array([[3, 5], [2, 1]])
array2 = array1.copy()
- Mathematics of two arrays
array1 = np.array([[3, 5]])
array2 = np.array([[2, 1]])#addition
array1 + array2#output: array([5, 6])#multiplication
array1*array1#output: array([9, 25])subtraction
array1-array1#output: array([1, 4])
When we want to do an operation between a scalar number and an array(vector) so, NumPy knows that the operation is done with all elements of an array. This is known as broadcasting.
array1 = np.array([[3, 5]])
array1*2#output: array([6, 10])
- Maximum, Minimum, and Sum
To find the max, min, and sum from the array.
array1 = np.array([[3, 5, 8]])
array1.max()
array1.min()
array1.sum()#output: 8
3
16
It is used to create a 2 axis matrix.
#2 rows and 2 columns
array1 = np.array([[3, 5], [2, 1]])
array1#output: array([[3, 5],
[2, 1]])#3 rows nd 2 columns
array1 = np.array([[3, 5], [2, 1], [4, 6]])
array1#output: array([[3, 5],
[2, 1],
[4, 6]])#indexing of 2D matrix
array1[1:3]#output: array([[2, 1],
[4, 6]])array1[0:2, 0]#output: array([3,
2])#find maximum when axis = 0 means column wise
array1.max(axis=0)#output: array([4, 6])#find maximum when axis = 1means row wise
array1.max(axis=1)#output: array([5, 2, 6]) #check row wise
- Generating a random number
We can generate a random number within a specific range. The parameter value 2 in the integers function decides the range in which the numbers be generated.
rng = np.random.default_rng(0)
rng.integers(2, size=(2, 4))#output: array([[1, 1, 1, 0],
[0, 0, 0, 0]], dtype=int64)#with new range value
rng.integers(5, size=(2, 4))#output: array([[4, 3, 2, 1],
[1, 0, 0, 0]], dtype=int64)
To know the total unique values in an array.
array1 = np.array([[3, 5, 2, 1, 4, 3, 4, 7 , 8]])
unique_values = np.unique(array1)#output: array([1, 2, 3, 4, 5, 7, 8])#to know the index number of unique_values as on first occurrence
unique_values, index_num = np.unique(array1, return_index=True)
print(index_num)#output: [3 2 0 4 1 8 9]#to know the number of times unique values are occurred
unique_values, occurrence_count = np.unique(array1,
return_counts=True)
print(occurrence_count)#output: array([1, 1, 2, 2, 1, 1, 1], dtype=int64)
The index_num output can be read like this, the value comes in unique_values list is first occurred on 3rd index and like so on. The occurrence of values means 3 and 4 occurred two times each in the raw array1.
The transpose will change the axis or dimension on the array.
array1 = np.array([[3, 5, 2], [1, 4, 6]])
array1.transpose()#output: array([[3, 1],
[5, 4],
[2, 6]])
It will make the array to 1-D from different dimensions.
array1 = np.array([[3, 5], [2, 1], [4, 6]])
array1.flatten()#output: array([3, 5, 2, 1, 4, 6])
Matplotlip plots of arrays
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
array1 = np.arange(-10, 10, 0.10)
array2 = np.arange(-7, 7, 0.20)
array1, array2 = np.meshgrid(array1, array2)R = np.sqrt(array1**2 + array2**2)
Z = np.sin(R)
ax.plot_surface(array1, array2, Z, rstride=1, cstride=1,
cmap='viridis')
Plot output:
Conclusion
The basic operations of arrays can be very helpful in numerical computations like algebra, mathematical formulations, matrices calculations, etc. I hope this article will give some insight into NumPy.
Reach me on my LinkedIn
- NLP — Zero to Hero with Python
2. Python Data Structures Data-types and Objects
3. MySQL: Zero to Hero