Numpy
Numpy
What is Numpy?
->It is the python library
->It is used to perform complex numerical problems
>By using python we slove basic mathematical problems
Ex: addition,sub , sqrt,
> By using numpy we can slove complex mathematical problems
Like : integral calculation, differential equations, statistics related topics(mean,median,mode)
Creating the arrays and performing operations on the array
->by default array concept is not available in the python instead we are using list
->It is the open source library
Creating an Array
We can create array in 2 ways:
By using array Module # We don’t use array module because there is not much library support
By using Numpy module
Note : If the list contains different type elements. The lower type element is converted into higher type
# Create a array for a particular datatype (using dtype argument)
list=[1,2,3,4,0]
arr=np.array(list,dtype=float)
print(arr) #[1. ,2. ,3. ,4. ,0.]
arr1=np.array(list,dtype=complex)
print(arr1) #[1. +0.j ,2. +0.j ,………….]
arr2=np.array(list,dtype=bool)
print(arr2) #[True,True,True,True,False]
arr4=np.array(list,dtype=str)
print(arr4) #[‘1’,’2’,’3’,’4’,’0’]
list1=[1.0,'',3,'Muk']
arr3=np.array(list1,dtype=bool)
print(arr3) #[True,False,True,True]
#linespace(start,stop,num=50) ,num=50 means 50 elements in the list, equaly spaced samples over
the intervals(start,stop)
arr1=np.linspace(1,30,5)
print(arr1) [1. 8.25 15.5 22.75 30. ]
arr=np.linspace(1,30,5,dtype=int)
print(arr) [1 8 15 22 30]
arr1=np.random.randint(10,20)
print(arr1) # Beyween 10 to 19
arr2=np.random.randint(10,100,size=10)
print(arr2) # creating an arry with size of 10
Arr5=np.random.randint(10,100,10)
arr3=np.random.randint(10,100,size=(3,4))
print(arr3) # creating 2D array 3 rows and 4 columns
arr4=np.random.randint(10,100,size=(4,3,4))
print(arr4) # creating an 3D array with 4 Blocks,3 rows in each block , 4 columns in each block
arr5=np.random.randint(10,100,10,dtype='float')
print(arr5) # It throws an error because we cannot change the dtype .default it was INT.
arr5=np.random.randint(10,100,10)
arr5_1=arr5.astype('str')
print(arr5_1) # we can use astype to change the dtype of the array.(obj_name.astype(‘dtype’))
#Random.rand
arr=np.random.rand(30)
print(arr) # It will 30 values.These values are ranges from [0 to 1]randomly it will print
#Random.uniform
arr=np.random.uniform(10,100,size=5)
print(arr)
arr1=np.random.uniform()
print(arr1) # It acts like a rand function (0 to 1)
arr2=np.random.uniform(10,20)
print(arr2)
#Shuffle Shuffling the array/ in multidimensional frist axis will shuffe
arr=np.random.randint(10,20,size=7)
print(arr)
np.random.shuffle(arr)
print(arr)
arr1=np.random.randint(10,20,size=(3,7))
print(arr1)
np.random.shuffle(arr1)
print(arr1) # 3 (axis=0) rows,7 (axis=1) columns
arr2=np.random.randint(10,20,size=(2,3,7))
print(arr2)
np.random.shuffle(arr2)
print(arr2) # 2 (axis=0) Blocks, 3 (axis=1) rows, 7(axis=2) columns, 0axis will shuffle
Array Attributes :
ndim = To get dimension of the array (arr.ndim)
Shape = to get shape of the array (arr.shape)
Dtype = to get data type of the elements (arr.dtype)
Size = to get size of the array(n.o of elements) (arr.size)
Iteamsize = it will give size of the array in bytes
Astype = to change the datatype of the array ( arr1.astype(‘str’) )
arr=np.array([1,2,3,4])
arr1=arr.astype('str')
print(arr1)
DataTypes:
Int ->int8(8 bits) , int(16), int(32), int(64) default (int32) I.e int8 array requires less space than int32
Float ->float(16), float(32), float(64) default(float64)
Indexing/Slicing
->To access/get the elements in the numpy array
->there are two ways
Indexing
Slicing
->Indexing:
We can access single element, zero based indexing , it supports +ve,-ve indexing
->Slicing
It is the way to access the subset of an array
It can access single element or Range of elements from array based on their indices.
Syntax : I[ : : ] ->Slice operator
I[Start : End-1 : Step] # Default for Start = 0
End = len(l)
Step = 1
#Acessing elements from 1D array
arr=np.random.randint(10,30,size=10)
print(arr)
arr[1:5:1]
print(arr[:4])
print(arr[:])
print(arr[: :])
print(arr[-7:-4]) # note : The elements retrive from left to Right (not) right to left
print(arr[-1:-3:-1])
Rules :
-> All the three (Strart,End,Step) are optional but the indentation is mandatory/necessary
-> Start,end,step the values can be +ve,-ve, but step can be Zero.
-> If the Step value is +ve = we can retrieve the elements in forward direction (start to end-1)
If the Step value is -ve = we can retrieve the elements in backward direction (start to end+1)
->In forward direction end value is 0 it means Empty array
In the back ward direction end value is -1 the array is empty.
#Array Slicing : I we the original array the copied array also changes.
arr=np.array((10,20,30,40,50,60,70,80,90))
arr1=arr[::]
arr[0]=99999
print(arr) #[99999 20 30 40 50 60 70 80 90]
print(arr1) #[99999 20 30 40 50 60 70 80 90]
#To iterate the elements of 2D array : Nested for loop ->loop inside another loop
arr1=np.random.randint(10,30,size=(3,3))
print(arr1)
for i in arr1:
for j in i:
print(j)
#To iterate the elements of 3d array : Nested for loop ->loop inside another loop
arr2=np.random.randint(10,30,size=(3,3,3))
print(arr2)
for i in arr2:
for j in i:
for k in j:
print(k)
Note : For iterating we required n n.o of loop . To overcome this loops using nditer()
#By using numpy nditer() function : it is designed to iterate to iterate elements of any dimensional
without using multiple loops
nditer : is a class present in the numpy library
nditer() : crearting an object for nditer class
flags=['buffered'] = to store the changed type elements.we required some space that is buffer
Note : The nditer() it will return elements and not return indexes . We need to go with ndenumerate()
arr=np.array([10,20,30])
print(arr+arr) #[20 40 60]
print(arr//arr) #[1 1 1]
print(arr**arr) #[1410065408 0 1073741824]
arrR=np.random.randint(10,30,size=(3,3)) #2D Array
print(arrR+arrR)
print(arrR//arrR)
print(arrR**arrR)
print("-------------------------------------")
arr1=np.array([10,20,30])
arr2=np.array([40,50,60])
print(arr1-arr2) #[-30 -30 -30]
print(arr1/arr2) #[0.25 0.4 0.5 ]
print(arr1%arr2) #[10 20 30]
arrRa=np.random.randint(10,30,size=(3,3)) #2D array
arrRan=np.random.randint(10,30,size=(3,3)) #2D array
print(arrRa-arrRan)
print(arrRan/arrRan)
print(arrRan%arrRan)
print('-------------------------------------')
Broad Casting :
->we can perform broad casting when two arrays are different Dimensions and shapes and size.
Syntax : array_obj_name.resize(new_shape)
->If the new array is larger than the original array. Then the new array is filled with the zeroes
->It is method present in the ndarray class
->The array which is existing will be modified
Ex:
arr=np.arange(1,7)
arr.resize(2,5)
print(arr)
Reshape()
->It is used to change the shape of the array. Not Size
->It will not create a new array object
->the reshape will happen without changing the original array
->the size must be matched
Resize()
->It is to change the size of the array. Automatically shape and Data will change
->It will create a new array object
->They my be chance of data change in resize()
->The size need not to be matched
Ravel()
->It is both numpy library function and method present in the ndarray class
Numpy.ravel(ndarrayObj,order=’C’)
ndarrayObj.ravel()
->If we perform any changes in the Ravel copy,Those changes will be reflected in the Original copy