0% found this document useful (0 votes)
5 views16 pages

Ai Python Codings

The document outlines various Python programming tasks related to data manipulation and analysis using Pandas, including creating DataFrames, evaluating models, and performing statistical functions. It also covers data visualization techniques using tools like Orange Data Mining and includes examples of dropout rate analysis over specific years. Each section provides code snippets and expected outputs for practical understanding.

Uploaded by

hemalathacraze
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Ai Python Codings

The document outlines various Python programming tasks related to data manipulation and analysis using Pandas, including creating DataFrames, evaluating models, and performing statistical functions. It also covers data visualization techniques using tools like Orange Data Mining and includes examples of dropout rate analysis over specific years. Each section provides code snippets and expected outputs for practical understanding.

Uploaded by

hemalathacraze
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Q PON VIDYASHRAM GROUP OF SENIOR SEC. SCHOOLS CLASS XII ARTIFICIAL INTELLIGENCE - PRACTICAL FILE (2025-2026) [Link] python code to create a Pandas DataFrame using any sequence data type. (a) Display the DataFrame (b) Display first 2 records (c) Display last 2 records (d) Display the number of missing values in the dataset. A [Link]~CAUSEILABIECINDownloads\Program.Ipyi31- — O x Fie fit Format fun Options Window Help # python code to create a pandas DataFrame using any sequence data type 4 Creating 2 DataFrame using a sequence (list of dictionaries) import pandas as pa data = "Name": “Alice Name" ge" {'Name’ ie", ee "Maths": 78), {tName":"Aswanth™ 3} «df= [Link](data) # a} Display the DataFrame print("DataFrame:in’, df) 4b} Display first 3 records pring("inFirst 3 Records:in", €thead{3)) 4c) Display last 3 records prin"inLast 3 Recordin, dftai(3) ae Values in Each Columnsin", [Link])) ln 23 Coo 1 IDLE She 3.114 - ao x File Type “help”, “copyright”, “credits” or “license()” for more Information. ~ RESTART: CUsers\LAB4PC14\Downlcads\Program_1.py DataFrame: Name Age Marks 0 Alice 22.0 85.0 1 Bob 21.0 90.0 2 Charlie 23.0 78.0 3 Ram 25.0 80.0 4 Ravi 30.0 70.0 5 Aswanth NaN Natl First 3 Records: Name Age Marks 0 Alice 22.0 85.0 1 Bob 21.0 90.0 2 Charlie 23.0 78.0 Last 3 Records: Name Age Marks 3 Ram 25.0 80.0 4 Ravi 30.0 70.0 5 Agwanth NaN Natl Missing Values in Each Column: Name 0 Age 1 Marks 1 dtype: inte Ln3)_ Coto [Link] a python program to evaluate a model 2 pegan2p-CilsUB#CIDtioypngan 2p B14 - 0 x Fle Et Fomat fun Opis Window Hep eee mets impor confusion matrix, accuracy score, precision score, recall score, ft score ® | Actual Pred bel | yal = 1,0 ,1,0,1,041,0 |rcved= 10.40.06 1,4.) | # Comping conion mae |cm=contison mati actualy red) rn ConfsioeMai cm) | Calling mes | Pcuacy= accra sorely acl y pred) [rest recon sorely actly red) |vecall= reall erly sal ype) |i =f sorely aca red) info asa) pring Precsion: precision’) rin cal ecll”) |ringre Scr: ) ’ teil Ge IDLEShell3.114 - ao x File Edit Shell Debug Options Window Help [ Python 3.41.4 (agslv3.11.4:d2340e, Jun 7 2023, 05:45:37) [MSC | vs904 6a bit (AMD6S)} on wind | Tape "help", "copyright", “rotie™ or “iconea)” for moro infor ar aan Confusion Matrix re [15] | Recuracy: 0. | Precision: 0.8333333333333334 Recall: 0,8333333335353534 Fv score: erosassz4 | Ln 2 Cok 3. Write a python program to add and delete rows and columns in DataFrame 1 ey nao DISORD BE _ = as 4# Python program to add and delete rows and columns in DataFrame, ‘import pandas as pd 4 Create a sample DataFrame data={'Name':['Alice’, "Bob, ‘Charlie’, "Age's [25, 30, 281, ‘City’: ['New York’, ‘London’, ‘Paris ]} f= [Link](data) prin{*Original Dataframes\n’, df] #1, Adding a new column ff’Salary'] = [60000, 70000, 65000) | print("\nDataFrame after adding ‘Salary’ column:\n", df) #2. Deleting column «= drop iy, ansea) print("\nDataFrame after deleting ‘City’ column:\n", df) #3, Adding a new row ‘David! ‘Age’: 35, Salary 85000, 'Bonus':90000} new_row 2 after adding a new row:\n", df] print("\nDataFr 184, Deleting a row df= dfdropl2) brint{"\nDataFrame after deleting ow with index 2"\n’, df) ‘Deleting multiple rows rows_to_drop = [0, 3] df= dfdrop(rows_to_drop) "\nDataframe after deleting rows with indices O and 3\n", df) est za — ox Fie dt Set Dg Ose, Window He “ype hep, "copyright, ered” or Teens" or more information. * = RESTART: Ci/Utery/Students/Dowaload/Kl STD/PROGRAM, 3.07 Original DataFrame: Name Age Cty © Ales 25 New York 1 Bob 30. London 2 Chute 26 Pace | Detarame after adding ‘Salary’ column Name Age chy Salary (© Ales 25 New York 60000 1 Beb 80 London 70000 2 Ohutle 26 Pare 65000 Datahrame after deleting iy column: Name Age Salary © Ale 25. 60000 1 bob $0 70000 2 ure 28 65000 | DataFrame shar adding anew row: ‘Name Age Salary © Ale 25. 60000 1 eb 30 70000 2 Ge 28 65000 3. David 35 85000, | Datarame after deleting ow with index 2: Name Age Slay 0 Ale 25 60000 41 Bob 30 70000 3 David 35 85000, “Datarame ater Name Age Salary 11 ob 30. 70000 etn ows with ndces Cand 3: 4, Write a python program to Implement Attributes of Data Frame 2 PROGRAM day CiUser/Students(Downleads(alSTO/PROGR. — OO % Fle Edt Format Run Options Window Hels ‘Python program to Implement Attributes of DataFrame a Import pandas as pd "Priya", Rahul), "Data 3","Data 4"), s{185, 92, 78, 83], index=["Data 1","Data 2", Data 3","Data 4")), . [Link]({"Cricket’,"Volleyball","Hockey"," Badminton” lax-["Data 1","Data 2","Data 3","Data 4"))} 4 Creating a data frame object, data_frame = [Link](dlict) # printing this data frame on output screen print (data_frame) # [Link] attribute for this data frame print{data_feame.index) # Implementing columns attribute for this data frame print{data_frame.columns) # Implementing shape attribute for this data frame print(data_frame.shape) # implementing headin) attribute for this data frame print{data_frame.head(2}) implementing tailin} attribute for this data frame print fare) ie ako Fle ug Opa ep Python 3.12.0 as) 12. 0ofseba, Ow 22023, 11889) [MSC 1835 6b AMDEA] © * i “ype copy, "redt rene) for mar inferaton RESTART Users SudesDownloasSTDJPROGRAM Ay Studet Nae Spor Ditat amav 65. ist Dita2 aha 92 Vole Datad Piya 78 Hoskey Ditad Rab 93 Sadnintn Inde Studer, ‘Wars ‘Spor, ype ote) (63) Studet Marks Sports uti Arn 65 Ciket Data? Naha $2 Voleybal Student ake Spots mas Pye TE Hodey Dated Rahal 82 Badminton 5. Write a python program to read a csv file and perform statistical function on the dataset, to check missing values, filling missing data. "program. [Link]- GiUUsersMABAPCIS/Desktopiprogr. «OX File Edit Format Run Options Window Help | import pandas as pd | # Load the dataset | df ~ pd.read_csv("[Link]") | # Display the first few rows of the dataset Print{"First 9 rows of the dataset") Prini{[Link]\)) | # Summary statistics (mean, std) prini("\nStatistical Summary:") | pring{dtmeand) | pantarstaoy | # Chock for missing values | eimeening Vahsow Co rini([Link]) # FIN missing vatues| | atitna([Link], inplace—True) | # Verity it missing values are filled | print’\nMiseing Values After Filling:") | Printatenati worm) | # save the cleaned datesot dito_csv("clesned_data.cev", Index=Falso) piini@\nCleaned data saved as ‘cloaned_data.cev") ine 19_Cot IDLE Shell 3.11.8 - a x Fite Edit Shell Debug Options Window Help. | Python 3.11.4 (tags/v3.11,4:d2340ef, Jun 7 2 023, 05: nwin32 Type *help", “copyright”, “credits” of ™ se()" for more information. 37) [MSC v.1934 64 bit (AMD64)] 0 RESTART: C:/Usors/LABAPC15/Desktop/pr ‘ogram_5.py First 5 rows of the dataset: ‘YearsExperience Salary ° 4.1 39343.0 1 13 46205.0 2 15 NaN 3 2.0 43525.0 4 22 39891.0 Statistical Summary: YearsExperience 3.438889 Salary 58322.062500 dtype: floate4 YoarsExporionco 1.428343 Salary 12785.872659 dtype: Mloaté4 ng Values Count: YearsExperience 1 Salary 3 dtypo: inte4 Missing Values After Filling: Yearsexperience 0 Salary ° dtype: inte Cleaned data saved a ‘cleanod_data.cev’ Unda Cok 0 [Link] a python program to evaluate regression model A *PROGRAM Sey-Cy/UeeH/LABIPCIS/Dowmloade(PROGRAM ApyGI — «EX Fle Eat Format Run Options Window Hels lating @ regression model Mean Absolute Error (MAE), ‘Moan Squared Error (MSE), ane F° sor: X, y= make Fegression|n_samples~100, n features-t, noise=10, random state~42) 2 Split into train and test sats X train, X tosh y- train y_ tost~ tral i20=0.2,random_stato=42 ost spligy y, tos # Train model ‘model = LinearRegression() ‘model. figX-train, y-tain) Predictions y_pred = [Link] test) # Evaluation metrics mae ~ mean absolute resus print MAE: {mac:.29° rine MSE: {mse:-20") Drint{" Scone: (e220) E nat Gono IDLE Shell 311.4 - a x File Edit Shell Debug Options Window Help. Python 3.11.4 (tags/v3.11.4:d2340ef, Jun 7 2023, 05:45:37) [MS C v.1934 64 bit (AMD64)] on win32 Type “help”, “copyright”, “credits” or “license()" for more info mation, >e> = RESTART: C:/Users/LAB4PC15/Downloads/PROGRAM_6.py Ln® Cok 0 7, Perform step wise procedure of Data Visualization using the Orange Data Mining — Tool. \ \ Arto, \z (@) ) vawrare ) \ | \ Hy \e a al NXg f i @ output 1 Senter Plat “Orange File Edt View Window Help e® ai is Be e @ 2 e eo ea e ef [erste = 2B Bw | A101 B-115012 +4 Violin Plt - Orange =o x File Edit View Window Help seqal lenge 5 aa a @ | a B10 th, Distbutions - Orange - ag x File Edit View Window Help oa © ine-setosa © ire versicolor Ps re Sinica x 20 10 6 445-5 536 63s 7 7s 8 Frequency sepal length =? 68 | 3 B-i010 8. Pridicting Diabetes using Decision Tree in Orange Data Mining tool. output 1 a 6 1a Select Correct Select Msclasified Showe Number of instances Clear Selection Adjust hyperparameters: k (Number of Neighbors): Default is 5, but try 3, 7, or 9, Distance Metric: Use Euclidean distance for continuous features. Weighting: Choose "Uniform" or "Inverse Distance" weighting Step 6: Evaluate the Model Drag the "Test & Score" widget and connect it to the KNN model and testing data, It calculates performance metrics like: Accuracy — Overall correctness of predictions Precision — How many predicted diabetics are actually diabetic? Recall — How well the model detects diabetic patients? Fl -Score — Balance between precision and recall. Step 7: Visualize the Results Use the "Confusion Matrix" widget to analyze model performance. It shows True Positives (TP), True Negatives (TN), False Positives (FP), and False ‘Negatives (FN). 9. Perform customer segmentation using k- Means clustering in Orange Data Mining and analyse the results. Sesmer Pot ie (®) a @ = a vate EE) 3. High Income - Low Spending (Careful Spenders). Step 7: Experiment with Different Cluster Counts Change the k-value to see how the segmentation changes Try adding Age to clustering to get different insights. Use the "Box Plot" widget to compare spending behavior across clusters. 10. Write a python program to find out dropout rates change during the years surrounding the MDMS launch?” import matplotiit plot as pit # Data for years and dropout rates -ars = [1994, 1998] dropout_rates = [17, 10] # Create a bar chart [Link](years, dropout_rates, color=['blue’, 'green']) # Add labels and title [Link]('Year") [Link](‘Dropout Rate (%)') plt-title('Dropout Rates Before and After MDMS') # Show dropout rate values on top of each bar for i in range(len(years)): [Link](years[i], dropout_rates[i] + 0.5, str(dropout_rates|i]) +'%', ha='center") # Set y-axis limit a bit higher for better visuals [Link](0, max(dropout_rates) + 5) # Display the plot [Link]() output Dropout Rates Before and After MDMS 20.0 gs 17% 10% 10.0 Dropout Rate (%) 75 50 25 a0 1994 1995 1996 1997 1998 Year

You might also like