CA325 Numpy Concepts.pdf

Full Transcript

Smt.Chandaben Mohanbhai Patel Institute of Computer Applications CHARUSAT, Changa BCA SEMESTER-V CA325: Foundation of Data Science NUMPY CONCEPTS NumPy is a Python library used for numerical and matrix computations. Numpy Features:...

Smt.Chandaben Mohanbhai Patel Institute of Computer Applications CHARUSAT, Changa BCA SEMESTER-V CA325: Foundation of Data Science NUMPY CONCEPTS NumPy is a Python library used for numerical and matrix computations. Numpy Features:  Fast Array Processing  NumPy arrays are more efficient than Python lists for large data.  Vectorized Operations  Perform element-wise operations without writing loops.  Multidimensional Arrays  Support for arrays of any dimension.  Integration  Works with other libraries like Pandas, Matplotlib, and Scikit-learn  We have list in python but NumPy provides array object that is much faster than lists  Array object of NumPy is known as “ndarray”.  We can create “ndarray” object using “array()”function.  NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and manipulate them very efficiently. (locality of reference concept) NUMPY COMMANDS Function Name of command Python code Creating Np.array import numpy as np array/vector ages = [16, 22, 39, 86] arr = np.array(ages) print(arr) Create array fill Np.zeros import numpy as np with zero ages = np.zeros((3,2)) arr = np.array(ages) print(arr) Create array fill Np.ones import numpy as np with one ages = np.ones((3,2)) arr = np.array(ages) print(arr) Create array with Np.arange import numpy as np start, stop, ar = np.arange(5, 25, 5) increment values print(ar) Array attributes Shape import numpy as np Dtype n1 = np.arange(5, 25, 5) Size print(n1) Smt.Chandaben Mohanbhai Patel Institute of Computer Applications CHARUSAT, Changa BCA SEMESTER-V CA325: Foundation of Data Science ndim print(n1.size) print(n1.dtype) print(n1.ndim) ---------------------------------- import numpy as np arr1=np.array([[1,2,3],[4,5,6],[7,8,9]]) print(arr1) print(arr1.shape) Basic operations + import numpy as np Addition - n1 = np.arange(5, 25, 5) Subtraction / n2=[1,2,3,4] Division * print(n1+n2) Multiplication ** Exponential Aggregate and Np.Sum import numpy as np statistical functions Np.Min n1 = np.arange(5, 25, 5) Np.Max n2=[1,2,3,4] Np.mean print(np.max(n1)) Np.std print(np.sum(n2)) Np.average print(np.mean(n1)) Np.median print(np.median(n1)) print(np.std(n2)) ------------------------------- import numpy as np n1= np.random.randint(3,6,10) print(n1.max()) import numpy as np marks = np.array([60,70,70,60,23,100 ]) avg = (round(np.average(marks),2)) print(avg) Reshaping array Reshape() import numpy as np Print mks=[10,29,22] horizontal/vertical n1 = np.array(mks) n2=n1.reshape((3,1)) print(n2) Combine multiple np.concatenate() import numpy as np arrays to one mks=[10,29] n1 = np.array(mks) n2=np.arange(5,25,10) print(n2) n3=np.concatenate((n1,n2)) print("merged=", n3) import numpy as np Smt.Chandaben Mohanbhai Patel Institute of Computer Applications CHARUSAT, Changa BCA SEMESTER-V CA325: Foundation of Data Science arr1=np.array([[1,2,3],[1,2,3]]) arr2=np.array([[4,5,6],[4,5,6]]) print(np.concatenate((arr1,arr2),axis=1)) #joining two arrays along rows Splitting array Np.array_split import numpy as np arr1=np.array([1,2,3,4,5,6,7,8,9,10]) print(np.array_split(arr1,4)) #splitting array into 4 pieces import numpy as np arr1=np.array([1,2,3,4,5,6,7,8,9,10]) arr2=np.array_split(arr1,5) print(arr2) print(arr2) print(arr2) print(arr2) print(arr2) Slicing of Array lower:upperlimit import numpy as np arr1=np.array([1,2,3,4,5,6,7,8,9]) print(arr1[1:4]) Generating Random.rand # Generate and print random float Random number import numpy as np print(np.random.rand()) import numpy as np N=5 salary = 5000+(8000-2000)* np.random.rand(N) print(salary) Random.randn import numpy as np Random.randint print(np.random.randn(1,2)) # Generate and print random number import numpy as np print(np.random.randint(3,6,10)) Permutation and Np.random.choice #Randomly print the values Combination of import numpy as np Values to be N=5 printed gen = np.random.choice(['Male', 'Female'], N, p=[0.6, 0.4]) print(gen) Searching value in Np.where() import numpy as np array arr1=np.array([1,2,3,1,2,3,1,2,3]) print(np.where(arr1 == 3)) #gives all indexes where value 3 is found Smt.Chandaben Mohanbhai Patel Institute of Computer Applications CHARUSAT, Changa BCA SEMESTER-V CA325: Foundation of Data Science import numpy as np arr1=np.array([1,2,3,4,5,6,7,8,9,10]) print(np.where(arr1%2 == 0)) #gives all indexes where value is even Sorting into array Np.sort() import numpy as np arr1=np.array([2,3,1,4,3,5,8,6]) print(np.sort(arr1)) Reverse of the Np.flipud() import numpy as np array arr1=np.array([2,3,1,4,3,5,8,6]) print(arr1) print(np.flipud(arr1)) #reversing the array import numpy as np arr1=np.array([1,2,3,4,5]) print(arr1) print(np.flip(arr1)) #flipping the 1D array USER INPUT Np.array import numpy as np Create array from Np.append arr1= np.array([]) user Input a=int(input("Enter the size of array")) print for i in range(a): v=int(input("Enter element :")) arr1= np.append(arr1, v) print(arr1) MATRIX CREATION Np.array import numpy as np 2X2 # create a 2x2 matrix 3X3 matrix1 = np.array([[1, 3], [5, 7]]) print("2x2 Matrix:\n",matrix1) # create a 3x3 matrix matrix2 = np.array([[2, 3, 5], [7, 14, 21],[1, 3, 5]]) print("\n3x3 Matrix:\n",matrix2) Matrix + import numpy as np Manipulation - # create a 2x2 matrix * m1 = np.array([[1, 3], [5, 7]]) Addition / print("Matrix 1:\n",m1) Subtraction m2 = np.array([[2, 3], [7, 14]]) Multiplication print("\n Matrix 2:\n",m2) Division Np.transpose # Finding product of two matrix Transpose Np.linalg.inv s=m1*m2 Inverse print("sum=") print(s) Smt.Chandaben Mohanbhai Patel Institute of Computer Applications CHARUSAT, Changa BCA SEMESTER-V CA325: Foundation of Data Science import numpy as np # create a 2x2 matrix m1 = np.array([[1, 3], [5, 7]]) print(np.transpose(m1)) import numpy as np # create a 2x2 matrix m1 = np.array([[1, 3], [5, 7]]) print(np.linalg.inv(m1)) multi-dimensional np.nditer #interation using “nditer” iterator object to import numpy as np iterate over arrays arr1=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) for k in np.nditer(arr1): print(k,end=" ") Slicing and Dicing in : import numpy as np matrix n_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) #(element at first row, second column) : print(n_array[0, 1]) #array([1, 2, 3]) (first row, all columns) : print(n_array[0, 0:3] ) # (first row, all columns): print(n_array[0, :]) #(all rows, second column): print(n_array[:, 1]) array_2d = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]) # Get the first two rows and the first three columns diced_array = array_2d[:2, :3] print(diced_array) Permutation and Np.choice #Randomly print the values Combination of import numpy as np Values to be N=5 printed gen = np.random.choice(['Male', 'Female'], N, p=[0.6, 0.4]) print(gen) Smt.Chandaben Mohanbhai Patel Institute of Computer Applications CHARUSAT, Changa BCA SEMESTER-V CA325: Foundation of Data Science Applications QUESTION Python code 1 Find the weighted mean of all marks import numpy as np marks = np.array([70,80,50,65,40,95 ]) avg = (np.average(marks,weights=[2,4,5,3,10,1])) print(avg)# output same import numpy as np Find the weighted mean of all marks( marks = np.random.randint(0,101,size=6) use random function to generate avg = (np.average(marks,weights=[2,4,5,3,10,1])) marks) print(avg)# output will be different on each passes 2 Print the vector or array in horizontal # Printing horizontal and vertical array ( one dim) and vertical format import numpy as np a1=np.array([1,2,3,4]) print(a1) for i in a1: print(i) 3 Print the matrix in horizontal and import numpy as np vertical format arr1=np.array([[1,2,3],[4,5,6]]) print(arr1) for i in arr1: for j in i: print(j) 4 Print 4x4 matrix in single line import numpy as np arr1=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) for i in arr1: for j in i: for k in j: print(k,end=" ") OR #interation using “nditer” import numpy as np arr1=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) for k in np.nditer(arr1): print(k,end=" ") 5 Print even numbers from array import numpy as np arr1=np.array([1,2,3,4,5,6,7,8,9,10]) for i in arr1: Smt.Chandaben Mohanbhai Patel Institute of Computer Applications CHARUSAT, Changa BCA SEMESTER-V CA325: Foundation of Data Science if i%2 == 0: print(i) else: continue 6 Creating Filter array import numpy as np Whichever value is True that value will arr1=np.array([1,2,3,4]) only visible filter_arr=[True,False,True,False] #creating the filter array arr2=arr1[filter_arr] #filtering the array1 print(arr2) 7 For Election booth, make new voter list import numpy as np which consists of the age group whose age=np.array([12,23,43,11,56,75,23,14,18]) age is greater than 18 only. filter_array=[] for i in age: if i>=18: filter_array.append(True) else: filter_array.append(False) voter_list=age[filter_array] print("Voter Age: ",voter_list) import numpy as np age=np.array([12,23,43,11,56,75,23,14,18]) filter_array = age >= 18 voter_list=age[filter_array] print("Voter Age: ",voter_list)

Use Quizgecko on...
Browser
Browser