Download as pdf
Download as pdf
You are on page 1of 51
611723, 11.07 PM Assignments and Projects ASSIGNMENTS AND PROJECTS Module 1 - Getting Started With Python Assignment - 1 © IElse Statement = Input the values of a and b as 10 and 20 respectively. Now check if a is greater or b is greater using if condition. Think about all the edge cases, and print the statements accordingly. a-10 b= 20 if a>b: print ("a is greater than b") elif a print("a is equal to b") else: print("a is smaller than b") a is smaller than b Assignment - 2 * Conditional Statements = Take three user inputs and print the greatest number from those inputs using if-else condition. Edge cases, if any, should also be handled float (input ("Please enter a= *)) float (input ("Please enter b = ")) float (input ("Please enter ¢ = ")) if a>banda>c: print ("the greatest number is", a) elif b >a and b> c: print("the greatest number is", b) elif c > a and c > b: print("the greatest number is", c) else: print("All number are same") Please enter a= 164 Please enter b = 164 Please enter c = 644 the greatest number is 644.¢ Assignment - 3 * Loops * Print the numbers from 1 to 10 using while loop localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 81 611723, 11.07 PM Assignments and Projects i-1 while i < 11: print(i) ised * Create alist that has 10, 23, 4, 26, 4, 75, 24, 54 values and with the help of while loop fetch the even numbers and print the numbers. numbers = [10, 23, 4, 26, 4, 75, 24, 54] even_nunbers = [] index = @ while index < Len(nunbers) if numbers[index] % 2 == 0: ‘even_nunbers .append(nunbers[index]) index += 2 print("Even nunbers are:", even_numbers) Even numbers are: [10, 4, 26, 4, 24, 54: * Create an array that has user defined inputs and with the help of for loop,fetch all the prime numbers and print the numbers. import numpy as np # Take user inputs to create the array size = int(input("Enter the size of the array: ")) array = [] for i in range(size: nun = int (input (“Enter element {}: array. append(num) format(i + 1))) # Function to check if a number is prime def is_prime(n if ned: return False for i in range(2, int(n ** @.5) + 1): if n Xi == 0: return False return True # Fetch and print the prime numbers from the array prime_nunbers = [] for num in array: localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 251 611723, 11.07 PM Assignments and Projects Af is_prime(num) : prine_nubers. append (num) print("Prime nunbers in the array are:", prime_numbers) Enter the size of the array: 10 Enter element 1: Enter element 2: Enter element 3 Enter element Enter element Enter element Enter element 7: 65 Enter element Enter element 952 Enter element 10: 464 Prime numbers in the array are: [2, 3, 5] Module 2 - Concept Of OOPs In Python Assignment - 1 * Function And Class #1. def + 1.Create a function named ‘factor’ that can only accept 1 argument. The function should return the factorial of that num * 1. Create a function named ‘check string’ the function should accept a string date from the user and the function should check ifthe user input contains the letter 's init, fit contains the letter’s’ then print- The string is containing the letters", if not then print- ‘The string doesn't contain the letter‘ * 1. Create a class named ‘student’ and inside the class, create a function named ‘fun1’- this method should accept the user defined input and return that value: a Create another method named- message() and that method should print the user defined input that we have defined in ‘funt” = 1. Create a lambda function that should double or multiply the number (that we will be passing in the lambda function) by 2. Store the lambda function in a variable named ‘double_num’ #1, Take user input string and check whether that string is palindrome or not. Function to calculate the factorial of a number: factor(n): factorial = 1 for i in range(1, n + 1): factorial *= i return factorial # Example: factor(4) 24 localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 3st 611723, 11.07 PM Assignments and Projects In [ # 2. Function to check if a string contains the Letter def check_string(string): if ‘s" in string: print(“The string is containing the letter ‘ else: print(“The string doesn't contain the letter # Example: check_string("rahul") The string doesn't contain the letter 's In [ # 3. Class ‘Student’ with methods ‘funi' and ‘message’: class Student: def funt(self, value): return value def message(self): value = self.funt(input("enter a value: ")) print("User-defined input:", value) # Example: # Create an object student student = Student() # Directly returning the user defined value using funt() method print(student fund (20) ) # Call the message() method student.message() 20 Enter a value: 10 User-defined input: 10 In [35]: # 4, Lambda function to double or multiply a number by 2: double_nun = lambda x: x *2 # Instead of using def to create a new function, we double_nun(1e@) 208 In [ # 5, Function to check if a string is @ palindrome: def is_palindrone(string) : string = string.lower() reversed_string = string[ if string == reversed_string print("The string is a palindrone”) else: print("The string is not a palindrome") 1) # Example: is_palindrone("Bobob") The string is a palindrome localhost 8888inbconverthiml Assignments and Projects. pynb?download=false ast 611723, 11.07 PM Assignments and Projects Assignment - 2 © 1. Create a class named ‘Super' and inside that class define a user-defined function named fun a, Inside the ‘funt" function, pass the message “This is function 1 in the Super class.” in the print statement * 1.Create another class named 'Modified_Super’ and inherit this class from the Super class 1 a, Inside the Modified Super class, create a function named ‘funt’ and pass the following message inside the print statement: This is function 1 in the Modified Super class: =. Create another user-defined function named ‘fun2’ and pass the message: ‘This is the 2 nd function from the Modified Super class’ in the print statement = c After that, now create an object for the Modified Super class and call the funt10. + 1.Create 2 methods named ‘Hello. In the 1st Hello method, pass only one argument anc pass this message: This function is only having 1 argument’. And in the 2nd Hello method, pass two arguments and pass this message: ‘This function is having 2 arguments. ® a, Ty to call both the methods and analyze the output of both the methods + 1,Create a method named 'Sum’ that can accept multiple user inputs. Now add those user defined input values using for loop and the function should return the addition of the numbers *1.Create a class named ‘Encapsulation’ © a, Inside the class, first create a constructor. Inside the constructor, initialize originalValue variable as 10. ® . After creating the constructor, define a function named ‘Value’ and this function should return the variable that we have initialized in the constructor. 1c. Now create a 2nd function named setValue, and pass an argument named ‘newValue’. The task of this function will be to replace the value of the originalValue variable by the value of newValue variable fn #1. class Super: def funa(self): print("This is function 1 in the Super class.") # Create an object of the Super class obj = Super() # Call the funt() method obj. fun() This is function 1 in the Super class n #2. class Modified_super(Super): def funt(self): print(*This is function 1 in the Modified Super class.) localhost 8888inbconverthiml Assignments and Projects. pynb?download=false sist 611723, 11.07 PM Assignments and Projects def fun2(self): print("This is the 2nd function from the Modified Super class.") # Create an object of the Modified Super class ‘obj = Modified_super() # Call the funi() method obj.funt() This is function 1 in the Modified Super class. In [42]: #3. Two methods named ‘HeLlo' with different number of arguments. class MyClass: def Hello(self, argi): print("This function is only having 1 argunent. def Hello(self, argi, arg2): print("This function is having 2 argunents.") # CaLL the Hello methods my_obj = MyClass() my_obj.Hello(1, 2) # This will call the method with two arguments This function is having 2 arguments. In [43]: # 4, Method ‘Sum’ to accept multiple user inputs and return their sum: def Sum(*args): total = @ for num in args: total += num return total # Call the Sum method result = Sum(1, 2, 3, 4, 5) print("Sum:", result) Sum: 16 In [45]: #5. Class ‘Encapsulation’ with a constructor and a function ‘Value': class Encapsulation: def _init_(self): self.originalValue = 10 def Value(self): return self.originalValue def setValue(self, newValue): self.originalValue = newValue # Create an object of the Encapsulation class encap_obj = Encapsulation() # COLL the Value method to retrieve the original value value = encap_obj.Value() print(“Original Value:", value) # Call the setValue method to update the value new_value = 20 localhost 8888inbconverthiml Assignments and Projects. pynb?download=false ast 611723, 11.07 PM Assignments and Projects encap_obj. setValue(new_value) # CaLl the Value method again to retrieve the updated value value = encap_obj.Value() print("Updated Value:", value) Original Value: 1¢ Updated Value: 20 class BankAccount: def _init_(self, initial): # It’s a object constructor that define default val Self.anount = initial # "amount" is a property of the "BankAccount" class def withdraw(self, amount: self.anount -= amount # "withdraw" is a method def deposit(self, amount): self.anount += amount def balance(self): return self.anount # Let me create an instance of ‘BankAccount' class with the initial balance as $2000. myAccount = BankAccount (2000) # "ayAccount” is an object # Let me check if the balance is right. print (nyAccount-balance()) # Let me deposit my salary myAccount .deposit (10000) # Let me withdraw some money to buy dinner. myAccount.withdraw(15) # what's the balance Left? print (nyAccount-balance()) 200¢ 11985 myAccount. anount 11985 Assignment - 3 * 1.Create a class named parent _Class and inside the class, ii as 1C ® a, Create another class named child_Class and this class should be inherited from the parent class. =. Now create an object for the child_Class and with the help of child_Class object, display the value of ‘num’, © 1. Create three classes named A, B and C = a, Inside the A class, create a constructor. Inside the constructor, initialize 2 global variables name and age ize a global variable num localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 751 611723, 11.07 PM Assignments and Projects 2. After initializing the global variables inside the constructor, now create ¢ function named ‘details’ and that function should return the ‘name’ variable. ® c Inside the B class, create a constructor. Inside the constructor, initialize 2 globa variables name and id = d. After initializing the global variables inside the constructor, now create 2 function named ‘details’ and that function should return the ‘name’ variable =, The C class should inherit from class A, and B. Inside the class C, create e constructor, and inside the constructor, call the constructor of class A Now, create a method inside the class C, as get details, and this function should return the value of name = 4g, Atlast, create an object of class C, and with the help of the object, call the get details * 1,Create a class named 'Sub1’, inside the class, generate a user defined function named ‘frst’ and inside the function, pass the following statement in the print0)- ‘This is the first function from Sub 1 class’ = a, Now create another class named ’Sub2’, and inside the class, create a function named ‘second’, and pass the following message in the print0- This is the seconc function from the Sub 2 class’ = 0. After that, create another class named ‘Super’ and inside that class, create @ method named ‘final’, and pass the below message in the print(- This is the final method from the super class’ ™ c.Now, create an object for the Super class and call all the 3 user defined methods, ie,, first), second0), and final0. * 1,Create a class named ‘Parent’, and inside the class, create a function named ‘funt’ anc 9ass the following message in the print(- This is the message from the fun! = a, Now create a class named ‘Child1' and inside the class, create a method named ‘fun2’ and pass the following message in the print) ‘This is the message from the fun2’. = 0. After that, create another class named ‘Child2 and inside the class, create a method named ‘fun3' and pass the following message in the print0- This is the message from the fun3’ = c. Now, create an object of Child2 class and with the help of the object, call the ‘funt’ method from the ‘Farent'class * 1.Create a class named ‘Farent’ and inside the class, create a function named ‘funt’ anc 9ass the following message in the print(- This is the message from the fun! = a, Now create a class named ‘Child’ and inside the class, create a method named “fun2’ and pass the following message in the print()- ‘This is the message from the fun2’. = b. After that, create another class named ‘Hybrid! and inside the class, create a method named ‘fun3' and pass the following message in the print()- This is the message from the fun3. = c.Now create an object of Hybrid class and with the help of the object, call the ‘fun, fun’ and ‘fun3’ methods localhost 8888inbconverthiml Assignments and Projects. pynb?download=false ast 611723, 11.07 PM Assignments and Projects In [71]: #4. Parent and Child classes: class Parent_Class: num = 18 class Child_Class(Parent_Class): pass # Create an object of Child Class child_obj = Child Class() # Access the value of ‘num’ using the child obj print (child_obj.num) 10 In #2. Classes A, 8, and C: class a: def _ init__(self): Self.name = "Joh self.age = 25 def details (self): return self.nane class 8: def _init_(self): Self.name = "Alice" self.id = 12345 def details (self): return self.nane class C(A, 8): def get_details(self): return self.nane # Create an object of class obj = C() # Call the get_details method to retrieve the value of ‘name” name = c_obj.get_details() print("Name:", name) Name: Johr In # 3. Subt, Sub2, and Super classes: class Sub1: def first(self): print("This is the first function from Sub1 class") class sub2: def second(self): print("This is the second function from the Sub2 class") class Super: def final (self): print("This is the final method from the super class") localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 9st 611723, 11.07 PM Assignments and Projects # Create an object of the Super class super_obj1 = Sub1() super_obj2 = Sub2() super_obj3 = Super() # Call all the user-defined methods super_obj1.first() super_obj2.second() super_obj3.final() This is the first function from Sub1 class This is the second function from the Sub2 class This is the final method from the super class #4, Parent, Childi, and Child2 classes: class Parent: def funt(self): print(*This is the message from the funt") class child (Parent): def fun2(self print(*This is the message from the fun2") class child2(Parent): def fun3(self): print("This is the message fron the fun3") # Create an object of the Child? class child2_obj = child2() # CaLL the ‘funi' method from the Parent class child2_obj..fun1() This is the message from the fund #5. Parent, Child, and Hybrid classes. class Parent: def fund (self): print("This is the message from the fun1") class child: def fun2(self): print("This is the message from the fun2") class Hybrid(child, Parent): def fun3(self): print(*This is the message from the fun3") # Create an object of the Hybrid class hybrid_obj = Hybrid() # Call the ‘funi", ‘fun2", and ‘fun’ methods hybrid_obj fund () hybrid_obj..fun2() hybrid_obj..fun3() localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 105 611723, 11.07 PM Assignments and Projects This is the message from the funt This is the message from the fun2 This is the message from the fun3 Module 3 - Statistics Assignment - 1 + 1.Create a table in excel, table should have 2 columns named x and y. = a,x’ column should have numbers from 1-$ ». 'y’ should have numbers 2, 4, 5, 4, 2 * c.Now calculate the mean of columns x and y d. Calculate the mode of column x . Calculate the standard deviation of column y * §. Atlast calculate the range of columns x and y seperately a i 2 a 4 | Mean (IE) Median 3 Mode 7 #N/A sD 1.581139 1.241641 Range 4 3 Module 4 - NumPy Assignment - 1 * 1.Create a list named ‘mylist’ that has the following elements: 10, 20, 30, ‘apple’, True, 8.10 = a, Now in the ‘myList’, append these values: 30, 40 = 0. After that, reverse the elements of the ‘myList’ and store that in ‘reversedList * 1.Create a dictionary with key values as 1, 2, 3 and the values as ‘data, ‘information’ and ‘text’ ® a. After that, eliminate the ‘text’ value from the dictionary = 0. Add ‘features’ in the dictionary = c.Fetch the ‘data’ element from the dictionary and display it in the output * 1.Create a tuple and add these elements 1, 2, 3, apple, mango in my_tuple * 1.Create another tuple named numeric_tuple consisting of only integer values 10, 20, 30, 40, 50: = a Find the minimum value from the numeric_tuple localhost 8888inbconverthiml Assignments and Projects. pynb?download=false vst 611723, 11.07 PM Assignments and Projects = b. Concatenate my_tuple with numeric tuple and store the result in r1 * c.Duplicate the tuple named my tuple 2 times and store that in ‘newdupli + 1.Create 2 sets with the names set! and set2, where set1 contains (1,2,3,4,5} and set2 contains (23,7,6,1} Perform the below operation = a. set] union set2 © 0. set! intersection set2 * c.setl difference set2 # 1. List Operations: mylist = [1¢, 20, 3¢, ‘apple’, True, 8.10] # Append values to myList myList. append(30) # Method 1 mylist.insert(3, 40) # Method 2 # Reverse the eLements of myList reversedList = list(reversed(mylist)) # or nyList.reverse()"" print("myList:", myList) print("reversedList:", reversedList) mylist: [1@, 20, 3¢, 40, ‘apple’, True, 8.1, 30] reversedlist: [30 8.1, True, ‘apple’, 40, 30, 20, 10] # 2. Dictionary Operations: mybict = {1: ‘data’, ‘information’, 3: ‘text'} # Eliminate ‘text’ from the dictionary myDict. pop(3) # Add ‘features’ to the dictionary myDict[4] = ‘features’ # Fetch the ‘data’ element from the dictionary data_elenent = myDict.get(1) print("data_elenent:", data_elenent) data_element: data # 3, TupLe Operations: my_tuple = (1, 2, 3, ‘apple’, ‘mango') numeric_tuple = (10, 20, 3, 40, 5) # Find the minimum value from numeric_tuple ‘minimum_value = min(numeric_tuple) print("Mininum value:", minimum_value) # Concatenate my_tuple with numeric_tuple ri = my_tuple + numeric_tuple print("Concatenated tuple:", ri) # Duplicate my tuple 2 times localhost 8888inbconverthiml Assignments and Projects. pynb?download=false rast 611723, 11.07 PM Assignments and Projects ny_tuple * 2 print("Duplicated tuple: newdupli) Ninimun value: 1@ Concatenated tuple: (1, 2, 3, ‘apple’, ‘mango’, 10, 20, 30, 40, 50) Duplicated tuple: (1, 2, 3, ‘apple’, ‘mango’, 1, 2, 3, ‘apple’, ‘mango’) # 4, Set operations: set set2 1 4, 5} = 4,2, 3 = 2, 3, 7, 6 I} # Union of set1 and set2 union_set = set1.union(set2) print("Union of seti and set2:", union_set) # Intersection of set1 and set2 intersection_set - setiintersection(set2) print("Intersection of seti and set2:", intersection_set) # Difference of set and set2 difference_set = seti.difference(set2) print("Difference of seti and set2:", difference_set) Union of seti and set2: {1, 2, 3, 4, 5, 6, 7} Intersection of seti and set2: {1, 2, 3) Difference of set1 and set2: {4, 5} Assignment - 2 © 1. Create a 3x3 matrix array with values ranging from 2 to 10. © 1.Create a NumPy array having user input values and convert the integer type to the float type of the elements of the array. For instance: Original array [1, 2, 3, 4] Array converted to a float type: [ 1. 2.3. 4! © 1.Write a NumPy program to append values to the end of an array. For instance: Original array: (10, 20, 30} . After that, append values to the end of the array: [10 20 30 40 50 60 70 80 90} * 1.Create two NumPy arrays and add the elements of both the arrays and store the result in sumArray. © 1. Create a 3x3 array having values from 10-90 (interval of 10) and store that in array! Perform the following tasks = a Extract the 1st row from the array =, Extract the last element from the array # 1. Create a 3x3 matrix array: import numpy as np matrix = np.arange(2, 11).reshape(3, 3) print("Matrix array: print(matrix) localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 135 611723, 11.07 PM Assionments and Projects, Natrix array: [2 3 4] [5 6 7] [8 9 10)) #2. Convert NumPy array to float type: user_input = input("Enter values separated by spaces: array = np.array(user_input.split(), dtype=int) float_array = array.astype(float) print("Original array:", array) print("Aarray converted to float type: float_array) Enter values separated by spaces: 10 14 12 2 2035 54 Original array: [1@ 1412 220 3 5 54] Array converted to float type: [10. 14. 12. 2. 20. 3. 5. 54.] # 3. Append values to an array: original_array = np.array((10, 20, 3]) values to_append = np.array([4®, 52, 68, 78, 82, 9]) appended_array = np.append(original_array, values_to_append) print (“Original array:", original_array) print(“Array after appending values:", appended_array) Original array: [10 20 30: Array after appending values: [10 20 30 40 50 69 70 80 90] # 4, Add elements of two arrays: arrayi = np-array([1, 2, 3]) array2 = np.array([4, 5, 6]) sumArray = array) + array2 print("Array 2:", array1) print("Array 2:", array2) print("Sum of arrays:", sumArray) Array 1: [1 2 3) Array 2: [45 6 Sum of arrays: [5 7 9: # 5. Extract rows and elements from an array: arrayl = np.arange(1®, 91, 10).reshape(3, 3) print(array1) # Extract the 1st row from the array first_row = arrayi[@] print("First row:", first_row) # Extract the Last element from the array last_elenent = array[-1, -1] print("Last elenent:", last_elenent) localhost 8888inbconverthiml Assignments and Projects. pynb?download=false ast 611723, 11.07 PM Assignments and Projects [1@ 26 30] 40 50 62] (70 86 90] First row: [10 20 30] Last element: 96 Module 5 - Data Manipulation Using Pandas Assignment - 1 1. Start off by importing the customer_churn.csv file in the jupyter notebook and store that in churn DataFrame. 1.From the churn DataFrame, select only 3rd, 7th, 9th, and 20th columns and all the rows and store that in a new Dataframe named newCols. 1. From the original DataFrame, select only the rows from the 200th index till the 100th index(inclusive) column, 1. Now select the rows from 20th index tll 200th index(exclusive) and columns from 2nd index tll 15th index value Display the top 100 records from the original DataFrame. Display the last 10 records from the DataFrame Display the last record from the DataFrame Now from the churn DataFrame, try to sort the data by the tenure columnaccording to the descending order. 1. Fetch all the records that are satisfying the following condition: ® a, Tenure>50 and the gender as ‘Female’ "= b. Gender as ‘Male’ and SeniorCitizen as 0 * c. TechSupport as ‘Yes’ and Churn as ‘No’ = d. Contract type as ‘Month-to- month’ and Churn as ‘Yes’ 1. Use a for loop to calculate the number of customers that are getting the tech support and are male senior citizens # 1. Inport the customer_churn.csv file and store it in the churn DataFrane: import pandas as pd churn = pd.read_csv(r"C:\Users\Nohit Bhakuni\Downloads\customer_churn-1.csv") churn.head(2) customerlD gender SeniorCitizen Partner Dependents tenure PhoneService Multipletines Int: 7590. . ; No phone vuvec Female 0 Yes Ne No eens 5875. cnvoe Male 0 Ne No 34 Yes No 2 rows x 21 columns localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 1851 611723, 11.07 PM Assignments and Projects n (105. #2. Select specific colums (3rd, 7th, 9th, and 2eth) newCols = churn.iloc{:, [2, 6, 8, 19]] newCols SeniorCitizen PhoneService 7038 7039 7040 7041 7042 7043 rows x 4 columns 0 No Yes Yes No Yes Yes Yes No Yes Yes InternetService TotalCharges DSL DSL Ds DSL Fiber optic Ds Fiber optic Ds Fiber optic Fiber optic 2985 18895 108.15 1840.75 151.65 19905 73629 346.45 306.6 5844.5 and all rows into a new DataFre n (a # 3. Select rows from the 200th index till the 100th index (inclusive): newRows = churn.iloc[2@@ : 1001] newRows localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 16st 611723, 11.07 PM Assignments and Projects customerlD gender SeniorCitizen Partner Dependents tenure PhoneService MultipleLines 9323- 0 < 200 cry Female a Ys No 27 Yes Ne asda. 9 < 201 gooey female 0 No No 14 Yes Ne 202 3363-DTIVD Viale a Ys Yes 71 Yes Yes 71a. ° 5 . 203 wang Mle 0 No Yes 13 Yes Ne 9142- o < 204 Ee Male 2 No No 44 Yes Ne 6641 0 : 996 oey “eral 2 No No 4 Yes Ne 1374. . . 997 haepy male 1 No No 4 ves Yes 998 2545-LXWW) Viale a Yes No 7 Yes Ne 3234- ° < 999 acy Male 2 No No 2 Yes Ne 8357- o . wooo Seo. “emale 2 No No 7 Yes Ne 801 rows x 21 columns # 4, Select rows from the 2eth index till the 20@th index (exclusive) and columns fron ewRows2 = churn.iloc[20:26@ , 2:15] newRows2 localhost 8888inbconverthiml Assignments and Projects. pynb?download=false vist 611723, 11.07 PM SeniorCitizen Partner 20 1 a 0 2 0 23 0 24 0 195 0 196 0 197 0 198 0 199 0 180 rows x 13 columns Ne Yes Ne Yes Yes Assignments and Projects Dependents tenure PhoneService MultipleLines No No No Yes No ves 1 12 No No phone No No Yes No No Yes Yes Yes No #5. Display the top 109 records from the original Dataframe: ‘top_100 = churn. head(10@) ‘top_1ee localhost 8888inbconverthiml Assignments and Projects. pynb?download=false InternetService Online Os. No No os ost Fiber optic No Fiber optic Fiber optic No Ne Ne Ne Ne rast 611723, 11.07 PM 95 96 7 98 99 customerlD. 7590- VHVEG 3575- GNVDE 3668- capyeK 7795- crocw 9237- HaITu 8637-WiIVR 9803-FUICG 0278- YxXOOG 3212- «xOCR 4598-XLKNJ gender Female Male Male Male Female Male Male Male 100 rows x 21 columns # 6, Display the Last 10 records from the DataFrame: last_1@ = churn. tail(10) last_18 Assignments and Projects izen Partner Dependents tenure PhoneService MultipleLines Yes No No No No No No localhost 8888inbconverthiml Assignments and Projects. pynb?download=false No No No No No No No No 34 n 52 No No No phone service Ne Ne No phone service Ne Ne Ne Ne 91st 611723, 11.07 PM Assignments and Projects customerlD gender SeniorCitizen Partner Dependents tenure PhoneService MultipleLines 7033 9767-FFLEM Male o No No 38 ‘Yes Ne 0639. . ; 7 7034 083° male 0 No No 67 ves ves 2456. 5 6 es 7035 cave Male 0 No No 19 Yes Ne T30- 5 No phone 70365 male o No No 2 Ne Nophone 2509. 5 2 . 7037 WGERO Female 0 No No 72 ‘Yes Ne 7038 6840-RESVB Male 0 ‘Yes Yes 24 Yes Yes 2234- oO 2 s 7039224 mate os ves 7 o ves 7040 4801-JZAZL_ =emale o ‘Yes Yes W Ne Boren senice 361- . . ror 88 ale 1 Yes No 4 ves ves 7042 3186-AIIEK Vole 0 No No 66 ves Ne 10 rows x 21 columns #7. Display the Last record from the DataFrane: last_record = churn.tail(1) last_record customerlD gender SeniorCitizen Partner Dependents tenure PhoneService MultipleLines 7042 3186-AJIEK — Viale 0 No No 6 Yes Ne 1 rows x 21 columns # 8. Sort the data by the tenure column in descending order: sorted_by_tenure = churn.sort_values(by= sorted_by_tenure ‘tenure’, ascending-False) localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 20051 611723, 11.07 PM Assignments and Projects customerlD gender SeniorCitizen Partner Dependents tenure PhoneService MultipleLines were acpy Wale 2 Yes Yes 2 Yes Yes 193 SY Female a Yes ves 2 ves ves 45a vale os No 72 ves Yes 483 ctcaremale 0 Yes No 7 Yes Yes 3266 Witt Female 0 Yes ves 2 ves Ne tose 357 ate os ves 0 ves Yes 3826 ag (Male 2 Wes Yes 0 Yes Yes 936 Sng cemale 2 Yes ves 0 ves Ne 6754 2775-SEFEE Vale 2 No ves 0 ves Yes 1340270 Female 0 (Ys ves 0 No Nephone 7043 rows x 21 columns #9, Fetch records based on specific conditions: condition_1 = churn{(churn['tenure'] > 5@) & (churn['gender') print (condition 1) condition_2 = churn[(churn['gender'] == ‘Male’) & (chura['SeniorCitizen] == @)] print (condition_2) condition_3 = churn{(churn['TechSupport’ } print (condition_3) condition_4 = churn[(churn[‘Contract" ] print (condition 4) Female" )] "Yes') & (churn{‘Churn'] == 'No')] Yes "Month-to-month") & (churn[ ‘Churn’ ] localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 2st 611723, 11.07 PM 15 16 23 30 35 7023 7028 7034 7037 7039 15 16 23 30 35 7023 7028 7034 7037 7033 15 16 23 30 35 7023 7028 7034 7037 7039 15 16 23 30 35 7023, 7028 7034 7037 7039 15 16 23 30 35 7023 custonerID gender 3655-SNQYZ Fenale 8191-X0SZ6 Fenale 3638-NEABW Female 3841-NFECK Fenale 6234-RAAPL_ Fenale 1035-IPQPU Female 9281-CEDRU Female 0639-TSIQW Female 2569-WGERO Female 2234-XADUH Female PhoneService Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes DeviceProtection Yes No internet service No Yes No Yes No Yes No internet service Yes StreamingMovies Yes No internet service No No No Yes No No No internet service Yes Yes No Yes Yes Yes Yes No Yes No Yes Assionments and Projects, SeniorCitizen Partner Dependents @ Fiber Fiber Fiber Fiber Fiber Fiber Techsuj Yes No Yes Yes Yes Yes Yes No No. Yes MultipleLines InternetService optic No DSL optic optic optic DSL optic No optic ipport. Yes No internet service Yes Yes Yes No Yes No No internet service No Contract PaperlessBilling Two year One year Two year Two year Two year Month-to-month Two year Month-to-month Two year one year PaymentMethod MonthlyCharges Credit card (automatic) Mailed check Credit card (automatic) Credit card (automatic) Bank transfer (automatic) Electronic check 1 1 localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 13.25 20.65 59.90 96.35, 99.99 03.50 tenure Yes 68 No 52 No 58 No a Yes R No 63 No. 68 No 7 No. R Yes R OnlineSecurity Yes No internet service No. Yes Yes No. No. Yes No internet service No. StreamingTV Yes No internet service No No Yes Yes Yes Yes No internet service Yes \ No No Yes Yes No Yes No Yes Yes Yes TotalCharges Churn 7895.15 No 1022.95 No 3505.1 No 6766.95 No 7251.7 No 6479.4 No 22181 611723, 11.07 PM 7028 7034 7037 7039 7027 7033, 7035 7038 7042 7027 7033, 7035 7038 7042 7027 7033, 7035 7038 7042 7027 7033, 7035 7038 7042 Assignments and Projects Contract, One year Month-to-month One year Month-to-month One year Month-to-month Month-to-month Month-to-month One year Two year 1889.5 108.15 1840.75 1949.4 3487.95, 931.55, 2625.25, 1495.1 1990.5, 6844.5, Bank transfer (automatic) 64.18 4326.25 No Credit card (automatic) 102.95 6886.25 Yes Bank transfer (automatic) 21.15 1419.4 No Credit card (automatic) 103.28 7362.9 No [1022 rows x 21 columns] CustomerID gender SeniorCitizen Partner Dependents tenure 5575-GNVDE Male @ Wo No 34 3668-QPYBK ale @ Wo No 2 7795-CFOCH Nale @ Wo No 45 1452-KI0VK Male @ Wo Yes 22 6388-TABGU Male @ Wo Yes 62 @550-DCKLH Male @ Wo No 3 9767-FFLEM Male @ Wo No 38 8456-QDAVC Male @ Wo No 19 6840-RESVB Male @ Yes Yes 24 3186-AJIEK Male @ No No 66 PhoneService MultipleLines InternetService OnlineSecurity Yes No DSL Yes Yes No DSL Yes No No phone service DSL Yes Yes Yes Fiber optic No Yes No ost Yes Yes No Ost No Yes No Fiber optic No Yes No Fiber optic No Yes Yes Ost Yes Yes No Fiber optic Yes DeviceProtection TechSupport StreaningTV StreamingNovies Yes No No No No No No No Yes Yes No No No No Yes No No No No No No Yes Yes Yes No No No No No No Yes No Yes Yes Yes Yes Yes Yes Yes Yes PaperlessBilling PaymentMethod MonthlyCharges TotalCharges No Mailed check 56.95 Yes Mailed check 53.85 No Bank transfer (automatic) 42.30 Yes Credit card (autonatic) 89.10 No Bank transfer (automatic) 56.15 No Mailed check 73.35 Yes Credit card (automatic) 69.58 Yes Bank transfer (automatic) 78.78 Yes Mailed check 84.80 Yes Bank transfer (automatic) 105.65 Churn No 1 localhost 8888inbconverthiml Assignments and Projects. pynb?download=false zat 611723, 11.07 PM 2 3 5 9 7027 7033, 7035 7038 7042 Yes No. No No. No No No No [2981 rows x 21 columns] der SeniorCitizen Partner Dependents tenure 3 ry 15 23 2a 7027 7028 7036 7038 7042 4 15 24 7027 7028 7036 7038 7042 4 15 23 24 7027 7028 7036 7038 7042 3 cy 15 23 24 7027 7028 CustomerID gent 7795-CFOCH Mi 5129-JLPIS Mi 3655-SNOYZ Fem: 3638-WEABW Fem 6322-HRPFA Mi fale lale ale ale iale @550-DcxLH Male 9281-CEDRU Female ‘7750-EVxNZ Fenale 6840-RESVB Male 3186-AJIEK Male PhoneService Assignments and Projects @ No No. Yes Yes Yes No. Yes No. Yes No. MultipleLines InternetService No No phone service Yes No Fiber opi Yes Yes Fiber op' Yes Yes Yes No Yes No Yes No No No phone service Yes Yes Yes No Fiber opi Dst tic tic DSL DSL Ds Ds Ds ost tic No No Yes No Yes No. No. No. Yes No. OnlineSecur: DeviceProtection TechSupport StreamingTV StreamingMovies Yes Yes Yes No No No No Yes Yes Yes PaperlessBilling No Yes No Yes No No No Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Bank trans’ E Credit Credit Credit Bank trans: No Yes Yes No No Yes Yes Yes Yes Yes No. Yes Yes No. No. Yes No. Yes Yes Yes 45, 25 68 58 49 B 68 2 24 66 ity Yes Yes Yes No. Yes No. No No Yes Yes Contract One year Month-to-month Two year Two year Month-to-month Month-to-month Two year One year One year Two year PaymentMethod MonthlyCharges TotalCharges fer (automatic) lectronic check ard (automatic) ard (automatic) ard (automatic) Mailed check fer (automatic) localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 42.30 105.50 113.25, 59.90 59.60 73.35 64.18 1840.75 2686.05, 7895.15 3505.1 2970.3, 931.55, 4326.25, 24st 611723, 11.07 PM 7036 7038 7042 3 “ 1s 23 2a 7027 7028 7036 7038 7042 churn No No No No No No. No. No No. No No Yes [1734 rows x 21 colunns] 2 4 3B 7018 7026 7032 7034 7041 7018 7026 7032 7034 7041 B 7018 7026 7032 7034 7041 2 4 custonerID 3668-QPYBK 9237-HQITU 9305-CDSKC 7892-POOKP (2280-X3GEX 1122-30TW 8775-CEBBI 6894-LFHLY 2639-TSIQN 8361-LTMKD. PhoneService Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Electronic check Mailed check Yes Bank transfer (automatic) Assignments and Projects 60.65 743.3 84.80 1999.5, 105.65, 6844.5, gender SeniorCitizen Partner Dependents tenure \ Male @ No No 2 Female @ Wo No 2 Fenale @ Wo No 8 Fenale @ Yes No 28 Male @ Wo No 48 Male @ Yes Yes 1 Fenale @ Wo No 8 Male 1 No No a Fenale e@ Wo No 67 Male 1 Yes No 4 MultipleLines InternetService OnlineSecurity \ No Ost Yes No Fiber optic No vee Yes Fiber optic No. Yes Fiber optic No. Yes Fiber optic No. No Fiber optic No se. No Ost No Yes Fiber optic No eee Yes Fiber optic Yes... Yes Fiber optic No wee DeviceProtection TechSupport StreamingTV StreamingMovies No No Yes Yes Yes No No No Yes No PaperlessBilling Yes Yes No. No No Yes No No. No No No. No No No Yes Yes Yes No No No Yes No No. No Yes Yes Yes No. No No No. No. Contract \ Month-to-month Month-to-month Month-to-month Month-to-month Month-to-month Month-to-month Month-to-month Month-to-month Month-to-month Month-to-month PaymentMethod MonthlyCharges TotalCharges \ Mailed check Electronic check localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 53.85, 70.78 108.15 151.65, 2561 611723, 11.07 PM Assignments and Projects 5 Yes Electronic check 99.65 820.5 8 Yes Electronic check 104.80 3046.05 B Yes Bank transfer (automatic) 103.70 5036.3 7018 Yes Mailed check 70.65 70.65 7026 Yes Bank transfer (automatic) 44,20 403.35, 7032 Yes Electronic check 75.75 75.75 7034 Yes Credit card (automatic) 102.95 6886.25 7041 Yes Mailed check 74.48 306.6 churn 2 Yes 4 Yes 5 Yes B Yes 1B Yes 7018 Yes 7026 Yes 7032 Yes 7034 Yes 7ea1 Yes [1655 rows x 21 columns] #10. Calculate the number of customers with tech support and are male senior citizens count = @ for index, row in churn. iterrows(): if row['TechSupport'] == "Yes" and row[ 'gender”] count += 1 Male’ and row['SeniorCitizen’ count. 119 condition = churn{(churn[“TechSupport" == "Yes") & (churn{’gender’] == ‘Male’) & (chur Len( condition) 11g Assignment - 2 * 1, Start off by importing the cars.csv file in the jupyter notebook + 1,Generate a line plot graph for the column ‘model’ and ‘hp = a, Map the ‘model’ column on the x-axis =, Map the ‘hp’ column on the y-axis ® c.Provide the x-axis label as Models of the cars = d. Provide the y-axis label as Horse-Fower of Cars * @.Set the ttle as Model Names vs HorsePower * 1,Generate a bar plot graph for the columns ‘carbs’ and ‘gear’ = a, Map the ‘carbs’ onto the x-axis. =, Map the ‘gear’ onto the y-axis * c Provide the x-axis label as Number of carburetors = d. Provide the y-anis label as Number of forward gears localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 26051 1793, 1.07 PM Assignments and Projets = @.Set the ttle as carbs vs gear * 1, Plot a histogram for the column ‘wt = a, Map the ‘wt’ onto the x-axis ™ b. Provide the x-axis label as ‘weight of the cars’ © c Provide the y-axis label as ‘Count "= d. Set the number of bins as 30 = @.Set the ttle as Histogram for the weight values * 1, Plot a pie chart for columns: ‘cy!’ and ‘model’ form the cars.csv data frame. #1, Plot the area chart for the columns: ‘am’ and ‘carb’ ™ a, Set the ‘am’ on the x-axis = b, Set the ‘carb’ on the y-axis ® c Provide the x-axis label as Transmission = d. Provide the y-axis label as Number of carburetors = ¢. Provide the ttle as Transmission vs Number of carburetors n (127. #4. Importing Libraries and cars.csv file import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv(r"C:\Users\Mohit Bhakuni\Downloads\cars-: df head(2) csv") model mpg cyl disp hp drat wt qsec vs am gear carb 0 — Mazda RX4 21.0 6 1600 11C 38 2620 1646 0 1 4 4 1 Mazda Rx4Wac 210 6 1600 110 38 2875 1702 0 1 4 4 n [132 # 2. Line plot graph model = df{ model" ] hp = df{'hp"] plt.figure(figsize = (6,4) Plt. plot (model, hp) plt.xlabel("Models of the cars") plt.xticks(rotation = 9¢) plt.ylabel('Horse-Power of Cars") plt.title('Model Names vs HorsePower’) plt.show() localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 281 6117123, 11.07 PM Assignments and Projects Model Names vs HorsePower 300 6 250 6 & 200 g é @ p 150 5 2 100 30 Fao SUE SOSSUN GU BEERUSAESeBT Ng oeN aesre 2U88 SERED YR o8 SER 2S5 SSR Ro Ye IBS ASS Boe Ngos eee ss Be SORE HCUL TOTES Uagl Se gob NaS Bone SeSebsecssu BS EeeO oe eee R GEES NEGgS UESSo uel SEER Rose E lyse Ss a2 vee Basso ee oeeee Egden O° F255088 SURGES Keeeg> g°8e gee *ese RangeIndex: 38 entries, @ to 25 Data colunns (total 2 columns) # Column Non-Null Count Dtype ® Years€xperience 38 non-null _—‘float 64 1 Salary 30 non-null —‘float64 dtypes: floate4(2) memory usage: 608.0 bytes n (145. df. describe() YearsExperience Salary count 30000000 30.00000¢ mean 5.313332 76003,000000 std 2.837888 27414429785 min 1.100000 37731.000000 25% 3.200000 56720.750000 50% ‘4.700000 65237:000000 75% 7.700000 100544,75000¢ max 10500000 122391.00000¢ n (146. dF. conr() | YearsExperience Salary YearsExperience 1.000000 0.978242 Salary 9978242 1.00000¢ n [148. X = df['Yearsexperience'].values.reshape(-1, 1) Y = df[‘Salary'].values # .values returns the values of the column as a NumPy array. # .reshape(-1, 1) is used to reshape # If you directly use X = df['YearsExperience'] without the .values.reshape(-1, 1) par # hhile it ts possible to use a pandas Series as input for training a Linear regressic # By using .values.reshape(-1, 1), we ensure that X is a 2-dimenstonal array with shap X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size-0.33, random_statc model = LinearRegression() model. Fit(X_train, Y_train) Y_pred = model. predict(x_test) r2 = r2_score(¥_test, ¥_pred) print("R2 Score:", r2) 22 Score: @.9553063138044949, localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 2161 611723, 11.07 PM Assignments and Projects Assignment 2 Load the dataset using pandas 1 1. Extract data from outcome column is a variable named Y 1. Extract data from every column except outcome column in a variable named X * 1 Divide the dataset into two parts for training and testing in 70% and 30% proportion 1 1 1 Create and train Logistic Regression Model on training set Make predictions based on the testing set using the trained model Check the performance by calculating the confusion matrix and accuracy score of the mode! import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, accuracy_score data = pd-read_csv(r"C:\Users\Mohit Bhakuni \Downloads\diabetes..csv") data.head(2) Pregnancies Glucose BloodPressure SkinThickness Insulin BMI DiabetesPedigreeFunction Age 0 6 148 n 38 0 336 0627 5¢ 1 1 85 66 2s 0 266 9351 31 data. info() Rangelndex: 768 entries, @ to 767 Data colunns (total 9 columns) ® Column Non-Null Count Dtype 2 Pregnancies 768 non-null int64 1 Glucose 768 non-null int64 2 BloodPressure 768 non-null int64 3 SkinThickness 768 non-null int64 4 Insulin 768 non-null int64 5 BMI 768 non-null Float64 6 DiabetesPedigreeFunction 768 non-null float64 7 Age 768 non-null inte4 8 Outcome 768 non-null int64 dtypes: floate4(2), int64(7) memory usage: 54.1 KE data.corr() localhost 8888inbconverthiml Assignments and Projects. pynb?download=false sat 611723, 11.07 PM Assignments and Projects Pregnancies Glucose BloodPressure SkinThickness Insulin = BMI. Pregnancies 1.000000 9.129459 0.141282. 0.081672 -0.073535 0.017683 Glucose 0129459 1.000000 9.152590 9057328 0331357 0.221071 BloodPressure 0.141282 0152590 1.000000 -—«-0.207371 0.088933 0281805 SkinThickness -0.081672 0057328 «0207371 «1.00000 0.436783 0392573 Insulin -0.073535 0331357 —0.088933-——~90436783_ 1.000000 0.197858 BMI —00176A3 927107" —n2aians §~——-9392573.197A59t.aonoNe DiabetesPedigreeFunction -0.033523 0.137337 0.041265 0.183928 0.18507" 0.140647 Age 0544341 0.263514 9.239528 0.113970 -0.042163 0.036242 Outcome 0.221898 0.46658 0.06506E «02074752 0.130548 0292695 “ , na # Extract data from the ‘outcome’ column as the target variable (¥) Y = data[‘Outcone" ] # Extract data from every column except the ‘outcome’ column as the input features (x) X = data.drop( "Outcome", axis=1) # Divide the dataset into training and testing sets Xtrain, X_test, Y_train, Y_test = train_test_split(x, Y, test_size: -3, random_state: # Create and train the Logistic Regression modet model = LogisticRegression() model. Fit(X_train, Y_train) # Make predictions based on the testing set Y_pred = model. predict(x test) # Calculate the confusion matrix cm = confusion matrix(¥_test, Y_pred) # As in our condition @ = Negative (non-diabe print("Confusion Matrix:") # The first cell of the confusion matrix is 1 print(cm) # Calculate the accuracy score accuracy = accuracy_score(Y_test, Ypred) # (121 + 58) / (121 + 50 + 30 + 30) print("Accuracy Score:", accuracy) # Thus, This model correctly predicts the Confusion Matrix: [121 3@: 30 50]] Accuracy Score: @.7402597402597403 C:\Python\1ib\site-packages\sklearn\1inear_model\_logistic.py:458: ConvergenceWarnir g: lbfgs failed to converge (status=1): STOP: TOTAL NO. of ITERATIONS REACHED LIMIT. Increase the number of iterations (max_iter) or scale the data as shown in https: //scikit-learn.org/stable/modules/preprocessing.html Please also refer to the documentation for alternative solver option: https: //scikit-learn.org/stable/modules/linear_model .html#logistic-regressior niter_i = _check_optimize_result( localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 34st 611723, 11.07 PM Assignments and Projects from sklearn import metrics cm_display = metrics .ConfusionMatrixDisplay(confusion matrix = cm, display labels = [¢ cn_display.plot() plt.show() 120 100 3 80 Ez 60 40 Predicted label # Calculate the precision score precision = metrics.precision_score(¥_test, Y_pred) print( "precision is:", precision) # Calculate the precision score recall = metrics.recall_score(¥_test, Y_pred) print( “recall is:", recall) # Calculate the precision score fi_score = metrics.fi_score(Y_test, Y_pred) print( "fi-score is:", f1_score) precision is: 0.625 recall is: 0.625 fi-score is: 0.625 Assignment - 3 - Decision Tree 1. Load the dataset using pandas 2. Extract data from outcome column is a variable named ¥ 3, Extract data from every column except outcome column in a variable named X 4, Divide the dataset into two parts for training and testing in 70% and 30% proportion 5, Create and train Decision Tree Model on training set 6, Make predictions based on the testing set using the trained mode 35151 611723, 11.07 PM Assignments and Projects 7. Check the performance by calculating the confusion matrix and accuracy score of the mode from sklearn.tree import DecisionTreeClassifier Y = datal‘Outcone" ] # Extract data from every column except the ‘outcome’ column as the input features (x) X = data.drop( ‘Outcome’, axis=1) # Divide the dataset into training and testing sets Xtrain, X test, Y_train, Y_test = train test_split(x, Y, test_size=0.3, randon_state: # Create and train the Logistic Regression modet model = DecisionTreeClassifier() model. fit(X_train, Y_train) # Make predictions based on the testing set Y.pred = model. predict(x test) # Calculate the confusion matrix cm = confusion matrix(Y_test, Y_pred) — # As in our condition @ = Negative (non-diabe print("Confusion Matrix:") # The first cell of the confusion matrix is i print(cm) # calculate the accuracy score accuracy = accuracy_score(Y_test, Ypred) # (121 + 58) / (121 + 50 + 30 + 30) print("Accuracy Score:", accuracy) Confusion Matrix: [108 43 [ 24 56]) Accuracy Score: @.70995670995671 # Calculate the precision score precision = metrics.precision_score(Y_test, Y_pred) print( "precision is:", precision) # Calculate the precision score recall = netrics.recall_score(Y_test, Y_pred) print( “recall is:", recall) # Calculate the precision score fi_score = netrics.fi_score(¥_test, Y_pred) print( "fi-score is:", #1_score) precision i: recall is: 0.7 fi-score is: @.6256983240223464 0. 5656565656565656 Assignment - 4 - Random Forest 1. Load the dataset using pandas 2. Extract data from outcome column is a variable named Y 3, Extract data from every column except outcome column in a variable named X 4. Divide the dataset into two parts for training and testing in 70% and 30% proportior 5. Create and train Random Forest Model on training set localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 3651 611723, 11.07 PM Assignments and Projets 6, Make predictions based on the testing set using the trained mode 7. Check the performance by calculating the confusion matrix and accuracy score of the mode from sklearn.ensenble import RandonForestClassifier Y = data[‘Outcone" ] # Extract dota from every column except the ‘outcome’ column os the input features (x) X = data.drop(‘Outcone', axis=1) # Divide the dataset into training and testing sets X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size-@.3, random_state: # Create and train the Logistic Regression model model = RandonForestClassifien() nodel.fit(X train, ¥_train) # Make predictions based on the testing set Y.pred = model. predict(x_test) # Calculate the confusion matrix cm = confusion matrix(Y test, Y_pred) # As in our condition @ = Negative (non-diabe print("Confusion Matrix:") # The first cell of the confusion matrix is 1 print(cm) # Calculate the accuracy score accuracy = accuracy score(¥_test, Ypred) # (121 + 58) / (121 + 50 + 30 + 3) print("Accuracy Score:", accuracy) Confusion Matrix: [123 28: [ 3@ se] Accuracy Score: @.748917748917748¢ # Calculate the precision score precision = metrics.precision_score(¥_test, Y_pred) print( "precision is:", precision) # Calculate the precision score recall = metrics.recall_score(¥_test, Y_pred) print( “recall is:", recall) # Calculate the precision score fi_score = metrics.fi_score(Y_test, Y_pred) print( "fi-score is:", fl_score) precision i: recall is: fl-score is 0.6410256410256411 0.625 .6329113924050633, Assignment - 5 - Naive Bayes from sklearn.naive_bayes import GaussianNB Y data ‘Outcone'] # Extract data from every column except the ‘outcome’ column as the input features (x) localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 37151 611723, 11.07 PM Assignments and Projects X = data.drop("Outcome", axis=1) # Divide the dataset into training and testing sets X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size-@.3, random_state: # Create and train the Logistic Regression modet model = GaussianNB() model. Fit(X_train, Y_train) # Make predictions based on the testing set Y.pred = model. predict(x_test) # Calculate the confusion matrix cm = confusion matrix(Y_test, Y_pred) # As in our condition @ = Negative (non-diabe print("Confusion Matrix’ # The first cell of the confusion matrix is 1 print(cm) # Calculate the accuracy score accuracy = accuracy_score(y_test, Ypred) # (121 + 58) / (121 + 50 + 30 + 30) print("Accuracy Score:", accuracy) Confusion Matrix: [119 32) 27 53]) Accuracy Score: @.7445887445887446 # Calculate the precision score precision = metrics.precision_score(¥ test, Y_pred) print( "precision is:", precision) # Calculate the precision score recall = metrics.recall_score(¥_test, Y_pred) print( “recall is:", recall) # Calculate the precision score fi_score = netrics.fi_score(Y_test, Y_pred) print( "fi-score is:", #1_score) precision is: @.6235294117647059 recall is: 0.6625 fl-score is: @.6424242424242423 Projects Python Project - 1: Analyzing Naming Trends using Python # Method 1 import pandas as pd import zipfile # Specify the path to the ZIP file zip_path = "C:/Users/Mohit Bhakuni/Downloads/names. zip" # Create an empty Datafrane to store the combined data from all text files Gf conbined = pd.Datafrane() # Extract and process each text file within the ZIP file localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 3851 611723, 11.07 PM Assignments and Projects with zipfile.ZipFile(zip_path) as z: # Iterate over each file in the ZIP archive for file_nane in z.nanelist(): 4 Check if the file is a text file if file_name.endswith(".txt"): a Extract the text file with z.open(file_name) as file: # Read the text file into a DataFrame df = pd.read_csv(file, sep=",", header-None, names = ["Name", "Age", # Append the data from the text file to the combined DataFrame df_conbined = pd.concat([df_combined, df]) # Reset the index of the combined DataFrame df_conbined = df_combined.reset_index(drop=True) 461 611723, 11.07 PM Assignments and Projects 166 Total births by sex and year Sex 2.04|\— F -—— M as 10 os 0.0 1880 1900 1920 1940 1960 1980 2000 Year # Method 2 - Using matplotlib import matplotlib.pyplot as plt # Line graph for ‘mM’ (males) plt.plot(total_births. index, total_births['M'], label="Male') # Line graph for ‘F" (females) plt.plot(total_births.index, total_births['F'], label="Fenale’) # Set Labels and title plt.xlabel(‘Year") plt.ylabel(‘Total Births’) plt.title('Total Births by Year for Males and Fenales') # Display Legend pit. legend() # Display the plot plt.show() localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 2020 47181 611723, 11.07 PM Assignments and Projects 1e6 _ Total Births by Year for Males and Females — Male 2.01 — Female Ls 2 =z a g 1.0 os 0.0 isso 19001920 import seaborn as sns import matplotlib.pyplot as plt sns.Lineplot(data=total_births, x= sns.Lineplot(data=total_births, plt.xlabel("Year") plt.ylabel( ‘Total Births’) 1940 1960 1980 2000 2020 Year Year’, y='M", Year’, y='F', plt.title('Total Births by Year and Sex’) pit. legend() plt.show() 40st 6117123, 11.07 PM 2.0 18 10 Total Births Os: 0.0 4.0 35 3.0 2.5 2.0 Total Births LS 10 05 0.0 Assignments and Projects 166 Total Births by Year and Sex — Male — female 1sg0 1900 1920 1940 1960 1980 2000 2020 Year 166 Total Births by Year 1gg0 1900 1920 1940 1960 1980 2000 2020 Year localhost 8888inbconverthiml Assignments and Projects. pynb?download=false 49161 611723, 11.07 PM Assignments and Projects # To display the Total Births axis (Y-axis) values in format of thousand (K) import matplotlib.ticker as ticker » label='Male") » label='Fenale") sns. Lineplot(data~ sns. Lineplot (dat: plt.xlabel( ‘Year*) plt.ylabel( ‘Total Births’) plt.title('Total Births by Year and Sex") plt-legend() # Format y-tick Labels as thousands formatter = ticker.FuncFormatter(lambda x, pos: '{:,.0f}'.format(x/1¢09) + °K’) plt.gca() .yaxis. set_major_formatter( formatter) plt.show() # In the Line of code ticker.FuncFormatter(Lambda x, po: # The Lambda function uses the string formatting method "{:, .OF}'. format (x/1000) + # The FuncFormatter constructor takes a function as an argunent that defines the forme # x represents the tick value, which is the numeric value of the tick on the axis. # pos represents the position of the tick, which is not used in this particular Lamt 1, .Of} -format(x/1000) to fc # (:,.0f}: This formats the tick value as a float with no decimal places and adds cc # x/1000: This expression divides the tick value x by 100 to convert it to thousanc # Finally, the Lambda function appends the 'K' suffix to represent thousands by concat # When the FuncFormatter is applied to the y-axis using plt.gca().yaxis. set_major_forn Total Births by Year and Sex — Male 2,000 | —— Female 1,500k = é £ 1,000k 2 500K oK 1880 1900 1920 1940 1960 1980 2000 2020 Year localhost 8888inbconverthiml Assignments and Projects. pynb?download=false sot 611723, 11.07 PM Assignments and Projects # Top 109 names used over all these years ( Popular Names ) ‘top_10@_names = df_new.groupby("Name").age(Total_Births = ‘top_10@_names Births", "sum")).reset_inc Name Total Births 0 James 5238523 1 John 5180158 2 Robert 4858236 3 Miche 4423430 4 Wiliam 4183494 95 Brendes 610047 96 Aaron 605834 97 Frances 98130 98 Pamela 596176 99 willie 95927 100 rows x 2 columns syst localhost 8888inbconverthiml Assignments and Projects. pynb?download=false

You might also like