NumPy
NumPy is often compared with normal Python list because both can store multiple values. But, NumPy arrays are designed for fast numerical computation, while Python lists are general-purpose containers.
import numpy as np
if __name__ == "__main__":
a = np.arange(1,6)
b = np.array([2,3,4,5,6])
print(a)
print(b)
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a//b)
# We can use different functions to create arrays using NumPy.
a = np.array([1, 2, 3]) # create array
print(a)
a = np.zeros(5) # [0. 0. 0. 0. 0.]
print(a)
a = np.ones(4) # [1. 1. 1. 1.]
print(a)
a = np.arange(1, 10) # numbers from 1 to 9
print(a)
a = np.linspace(0, 10, 5) # 5 numbers between 0 and 10
print(a)
arr = np.array([1, 20, 13, 41])
# < p > < b > Mathematical functions: < / b > < br >
print("Sum: ",np.sum(arr)) # sum
print("Mean: ",np.mean(arr)) # average
print("Maximum of array: ",np.max(arr)) # maximum
print("Minimum of array: ",np.min(arr)) # minimum
print("Square root of each number of array: ",np.sqrt(arr)) # square root
# Shape and size functions
arr = np.array([[11,22,33],[3,4,5]])
print("dimensions of array: ",arr.shape)
print("number of elements in the array: ", arr.size)
print("number of dimensions of array: ", arr.ndim)
When working with NumPy arrays, we often need to access specific elements or parts of the array. NumPy provies indexing and slicing methods that make it easy to retrieve or modify values quickly.
arr = np.array([10,20,30,40,50])
print("First element: ",arr[0])
print("Second element: ",arr[1])
print("Last element: ",arr[-1])
print("Second Last element: ",arr[-2])
arr2 = np.array([[1,2,3],[4,5,6],[7,8,9]]) # 2D Arrays [Matrices]
print("First element:",arr2[0])
print("Second element:",arr2[1])
print("Last element: ",arr2[-1])
print("First element of first list:",arr2[1][0])
# Slicing means selecting a range of elements from an array.
# array[start : end: step]
# start: starting index
# end : ending index
print(arr[1:3])
print(arr2[1:3])
print(arr2[0:2, 1:3]) #rows 0 to 1 and columns 1 to 2