Important IP Programs
Master your practical exams with our curated list of essential Python programs for Class 12 Informatics Practices. Click on any program to view the code, copy it, or run it instantly.
In each topic the programs go from Easy to Hard. A CBSE tag shows the paper or practical list a program comes from; Rare marks less common programs that are still in the syllabus.
SERIES - CREATION 9 programs
-
A Series is a one-column list with an index. Without your own index, pandas numbers the items 0, 1, 2 ...
import pandas as pd marks = [78, 92, 85, 64] s = pd.Series(marks) print(s) # Output: # 0 78 # 1 92 # 2 85 # 3 64 # dtype: int64 -
Give each value a label with index=. Here the labels are month names.
import pandas as pd days = [31, 31, 30, 31] months = ['July', 'Aug', 'Sept', 'Oct'] s = pd.Series(days, index=months) print(s) # Output: # July 31 # Aug 31 # Sept 30 # Oct 31 # dtype: int64 -
The dictionary keys become the index and the values become the data.
import pandas as pd stock = {'Pens': 150, 'Erasers': 80, 'Sharpeners': 60, 'Notebooks': 200} Inventory = pd.Series(stock) print(Inventory) # Output: # Pens 150 # Erasers 80 # Sharpeners 60 # Notebooks 200 # dtype: int64 -
One value repeated for every index label.
import pandas as pd s = pd.Series(100, index=['X1', 'X2', 'X3', 'X4', 'X5']) print(s) # Output: # X1 100 # X2 100 # X3 100 # X4 100 # X5 100 # dtype: int64 -
Make a NumPy array with np.array(), then turn it into a Series.
import pandas as pd import numpy as np arr = np.array(['a', 'b', 'c']) s = pd.Series(arr, index=['first', 'second', 'third']) print(s) # Output: # first a # second b # third c # dtype: object -
Complete-the-code question: the index holds the animal names.
import pandas as pd data = ['Mammal', 'Mammal', 'Fish'] indx = ['Dog', 'Cat', 'Goldfish'] s = pd.Series(data, index=indx) print(s) # Output: # Dog Mammal # Cat Mammal # Goldfish Fish # dtype: object -
Create a Series from a dictionary of national parks and print the state of Sariska.
import pandas as pd di = {'Corbett': 'Uttarakhand', 'Sariska': 'Rajasthan', 'Kanha': 'Madhya Pradesh', 'Gir': 'Gujarat'} NP = pd.Series(di) print(NP['Sariska']) # Output: # Rajasthan -
Predict-the-output question: list * 2 repeats the list before the Series is made.
import pandas as pd list1 = [-10, -20, -30] ser = pd.Series(list1 * 2) print(ser) # Output: # 0 -10 # 1 -20 # 2 -30 # 3 -10 # 4 -20 # 5 -30 # dtype: int64 -
Error-finding question. Mistakes fixed: Pandas -> pandas, [ ] -> { }, p.Series(s) -> pd.Series(stud).
import pandas as pd stud = {'Name': 'Ramya', 'Class': 11, 'House': 'Red'} s = pd.Series(stud) print(s) # Output: # Name Ramya # Class 11 # House Red # dtype: object
Recommended books optional
Practise more for the board exam. Want more board-style questions and programs than this page has? These printed books are optional extras.
-
Together With CBSE Question Bank — Informatics PracticesSee price on Amazon
Class 12 · Chapterwise & topicwise · for the 2027 exam
-
Sumita Arora — Informatics Practices with PythonSee price on Amazon
Class 12 · 2026–27 edition · Dhanpat Rai & Co.
-
Arihant All in One — Informatics PracticesSee price on Amazon
Class 12 · Theory + practice questions
You don't need to buy anything: the notes, programs, quizzes and papers on CSIP12 are free. As an Amazon Associate, CSIP12 earns from qualifying purchases.
SERIES - ATTRIBUTES, INDEXING & SLICING 7 programs
-
head(n) shows the first n values and tail(n) the last n. Without n, both show 5.
import pandas as pd s = pd.Series([10, 20, 30, 40, 50, 60, 70]) print(s.head(3)) print(s.tail(2)) # Output: # 0 10 # 1 20 # 2 30 # dtype: int64 # 5 60 # 6 70 # dtype: int64 -
Attributes describe the Series. They are written without brackets.
import pandas as pd s = pd.Series([45, 12, 15], index=['mouse', 'printer', 'webcam']) print(s.index) print(s.values) print(s.size) print(s.dtype) # Output: # Index(['mouse', 'printer', 'webcam'], dtype='object') # [45 12 15] # 3 # int64 -
Use the label with loc[ ] and the position (from 0) with iloc[ ].
import pandas as pd s = pd.Series([45, 12, 15, 200], index=['mouse', 'printer', 'webcam', 'keyboard']) print(s.loc['webcam']) # by label print(s.iloc[0]) # by position: the first value print(s[['mouse', 'keyboard']]) # Output: # 15 # 45 # mouse 45 # keyboard 200 # dtype: int64 -
Predict-the-output question: s[1:3] gives positions 1 and 2 (the end position is not included).
import pandas as pd com = pd.Series([45, 12, 15, 200], index=['mouse', 'printer', 'webcam', 'keyboard']) print(com[1:3]) # Output: # printer 12 # webcam 15 # dtype: int64 -
With labels, the end label IS included.
import pandas as pd com = pd.Series([45, 12, 15, 200], index=['mouse', 'printer', 'webcam', 'keyboard']) print(com['printer':'keyboard']) print(com[::-1]) # all values in reverse order # Output: # printer 12 # webcam 15 # keyboard 200 # dtype: int64 # keyboard 200 # webcam 15 # printer 12 # mouse 45 # dtype: int64 -
A condition in [ ] keeps only the values for which it is True.
import pandas as pd marks = pd.Series([78, 92, 45, 85, 33], index=['Riya', 'Aman', 'Sara', 'Kabir', 'Neha']) print(marks[marks >= 80]) print(marks[marks < 40]) # Output: # Aman 92 # Kabir 85 # dtype: int64 # Neha 33 # dtype: int64 -
quantile(0.75) gives the 75th percentile; then keep only the values above it.
import pandas as pd s = pd.Series([12, 45, 67, 23, 89, 34, 90, 56]) q75 = s.quantile(0.75) print("75th percentile:", q75) print(s[s > q75]) # Output: # 75th percentile: 72.5 # 4 89 # 6 90 # dtype: int64
SERIES - MATHEMATICAL OPERATIONS 5 programs
-
The operation is done on every value of the Series.
import pandas as pd price = pd.Series([100, 250, 80], index=['Pen', 'Bag', 'Ruler']) print(price + 10) print(price * 2) # Output: # Pen 110 # Bag 260 # Ruler 90 # dtype: int64 # Pen 200 # Bag 500 # Ruler 160 # dtype: int64 -
Common functions that work on the whole Series.
import pandas as pd marks = pd.Series([78, 92, 85, 64]) print("Total:", marks.sum()) print("Average:", marks.mean()) print("Highest:", marks.max()) print("Lowest:", marks.min()) # Output: # Total: 319 # Average: 79.75 # Highest: 92 # Lowest: 64 -
Values with the same label are added together.
import pandas as pd term1 = pd.Series([40, 35, 45], index=['Riya', 'Aman', 'Sara']) term2 = pd.Series([42, 30, 48], index=['Riya', 'Aman', 'Sara']) print(term1 + term2) # Output: # Riya 82 # Aman 65 # Sara 93 # dtype: int64 -
Predict-the-output question: a label found in only one Series gives NaN (no value).
import pandas as pd s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c']) s2 = pd.Series([4, 5, 6], index=['b', 'c', 'd']) print(s1 + s2) # Output: # a NaN # b 6.0 # c 8.0 # d NaN # dtype: float64 -
add() with fill_value=0 treats a missing label as 0 instead of giving NaN.
import pandas as pd s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c']) s2 = pd.Series([4, 5, 6], index=['b', 'c', 'd']) print(s1.add(s2, fill_value=0)) # Output: # a 1.0 # b 6.0 # c 8.0 # d 6.0 # dtype: float64
DATAFRAME - CREATION 7 programs
-
Each key becomes a column name. (Corrected code: import, pd.DataFrame and print are in lowercase.)
import pandas as pd df = {"Technology": ["Programming", "Robotics", "3D Printing"], "Time (in months)": [4, 4, 3]} df = pd.DataFrame(df) print(df) # Output: # Technology Time (in months) # 0 Programming 4 # 1 Robotics 4 # 2 3D Printing 3 -
Each inner list is one row; columns= gives the column headings.
import pandas as pd data = [["Divya", "HR", 95000], ["Mamta", "Marketing", 97000], ["Payal", "IT", 980000], ["Deepak", "Sales", 79000]] df = pd.DataFrame(data, columns=["Name", "Department", "Salary"]) print(df) # Output: # Name Department Salary # 0 Divya HR 95000 # 1 Mamta Marketing 97000 # 2 Payal IT 980000 # 3 Deepak Sales 79000 -
Each dictionary is one row; its keys are the column names.
import pandas as pd data = [{'Student': 'Aarav', 'Marks': 85}, {'Student': 'Aisha', 'Marks': 90}, {'Student': 'Vivaan', 'Marks': 78}, {'Student': 'Meera', 'Marks': 92}] df = pd.DataFrame(data) print(df) # Output: # Student Marks # 0 Aarav 85 # 1 Aisha 90 # 2 Vivaan 78 # 3 Meera 92 -
index= gives each row its own label instead of 0, 1, 2 ...
import pandas as pd voters = [{'Voter_Name': 'Arjun', 'Voter_Age': 35}, {'Voter_Name': 'Bala', 'Voter_Age': 23}, {'Voter_Name': 'Govind', 'Voter_Age': 25}, {'Voter_Name': 'Dhruv', 'Voter_Age': 19}, {'Voter_Name': 'Navya', 'Voter_Age': 18}] labels = ['Ar1001', 'Ba3002', 'Go4002', 'Dh4007', 'Na6005'] df = pd.DataFrame(voters, index=labels) print(df) # Output: # Voter_Name Voter_Age # Ar1001 Arjun 35 # Ba3002 Bala 23 # Go4002 Govind 25 # Dh4007 Dhruv 19 # Na6005 Navya 18 -
A key missing from one dictionary becomes NaN in that row.
import pandas as pd dict1 = {'a': 10, 'b': 20} dict2 = {'a': 5, 'b': 10, 'c': 20} df = pd.DataFrame([dict1, dict2]) print(df) # Output: # a b c # 0 10 20 NaN # 1 5 10 20.0 -
Each Series becomes one column.
import pandas as pd data = {'Items': pd.Series(['Bread', 'Milk', 'Eggs']), 'Quantity': pd.Series([50, 100, 120]), 'Unit_Price': pd.Series([30, 25, 6])} StoreDF = pd.DataFrame(data) print(StoreDF) # Output: # Items Quantity Unit_Price # 0 Bread 50 30 # 1 Milk 100 25 # 2 Eggs 120 6 -
Complete-the-code question: all the Series use the same index 10, 16, 18.
import pandas as pd S1 = pd.Series(['Rubina', 'Jaya', 'Vaibhav'], index=[10, 16, 18]) S2 = pd.Series(['IP', 'HSc', 'IP'], index=[10, 16, 18]) S3 = pd.Series([56, 67, 86], index=[10, 16, 18]) xiia = {'Name': S1, 'Subject': S2, 'Marks': S3} df = pd.DataFrame(xiia) print(df) # Output: # Name Subject Marks # 10 Rubina IP 56 # 16 Jaya HSc 67 # 18 Vaibhav IP 86
DATAFRAME - ATTRIBUTES & DISPLAY 3 programs
-
Create an exam result DataFrame and display the row labels, column labels, data types and dimensions.
import pandas as pd result = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara'], 'Marks': [88, 75, 93], 'Grade': ['A', 'B', 'A']}) print("Row labels:", result.index) print("Column labels:", result.columns) print(result.dtypes) print("Shape (rows, columns):", result.shape) print("Dimensions:", result.ndim) print("Total values:", result.size) # Output: # Row labels: RangeIndex(start=0, stop=3, step=1) # Column labels: Index(['Name', 'Marks', 'Grade'], dtype='object') # Name object # Marks int64 # Grade object # dtype: object # Shape (rows, columns): (3, 3) # Dimensions: 2 # Total values: 9 -
head()/tail() show the first/last rows; T swaps rows and columns.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara', 'Kabir'], 'Marks': [88, 75, 93, 67]}) print(df.head(2)) print(df.tail(1)) print(df.T) # Output: # Name Marks # 0 Riya 88 # 1 Aman 75 # Name Marks # 3 Kabir 67 # 0 1 2 3 # Name Riya Aman Sara Kabir # Marks 88 75 93 67 -
Predict-the-output question: df.size counts all values; df[1:3] gives rows 1 and 2.
import pandas as pd df = pd.DataFrame({'Store': ['Store1', 'Store2', 'Store3'], 'Qtr1': [300, 350, 250], 'Qtr2': [240, 340, 180], 'Qtr3': [450, 403, 145], 'Qtr4': [230, 210, 160]}) print(df.size) print(df[1:3]) # Output: # 15 # Store Qtr1 Qtr2 Qtr3 Qtr4 # 1 Store2 350 340 403 210 # 2 Store3 250 180 145 160
DATAFRAME - SELECTING DATA 6 programs
-
df['col'] gives one column; df[['a', 'b']] (double brackets) gives many.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara'], 'Class': [12, 12, 11], 'Marks': [88, 75, 93]}) print(df['Name']) print(df[['Name', 'Marks']]) # Output: # 0 Riya # 1 Aman # 2 Sara # Name: Name, dtype: object # Name Marks # 0 Riya 88 # 1 Aman 75 # 2 Sara 93 -
loc uses row labels; iloc uses positions counted from 0.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara'], 'Marks': [88, 75, 93]}, index=['r1', 'r2', 'r3']) print(df.loc['r2']) # one row by label print(df.iloc[0]) # first row by position print(df.loc['r1':'r2']) # rows r1 to r2 (r2 included) # Output: # Name Aman # Marks 75 # Name: r2, dtype: object # Name Riya # Marks 88 # Name: r1, dtype: object # Name Marks # r1 Riya 88 # r2 Aman 75 -
Give the row label and the column name.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara'], 'Marks': [88, 75, 93]}) print(df.loc[1, 'Name']) print(df.at[2, 'Marks']) # Output: # Aman # 93 -
Show which rows have more than 1 attempt, the last three records, and rows a and d.
import pandas as pd result = pd.DataFrame({'Name': ['Atulya', 'Disha', 'Kavita', 'John'], 'Score': [12.5, 9.0, 16.5, 15.0], 'Attempts': [1, 3, 2, 1], 'Qualify': ['yes', 'no', 'yes', 'no']}, index=['a', 'b', 'c', 'd']) print(result.loc[:, 'Attempts'] > 1) print(result.tail(3)) print(result.loc[['a', 'd']]) # Output: # a False # b True # c True # d False # Name: Attempts, dtype: bool # Name Score Attempts Qualify # b Disha 9.0 3 no # c Kavita 16.5 2 yes # d John 15.0 1 no # Name Score Attempts Qualify # a Atulya 12.5 1 yes # d John 15.0 1 no -
Put a condition inside df[ ] to keep only the rows where it is True.
import pandas as pd data = [{'Name': 'Aarav', 'Age': 24}, {'Name': 'Priya', 'Age': 30}, {'Name': 'Kunal', 'Age': 28}] df = pd.DataFrame(data) print(df['Age'] > 25) # True / False for each row print(df[df['Age'] > 25]) # only the rows where it is True # Output: # 0 False # 1 True # 2 True # Name: Age, dtype: bool # Name Age # 1 Priya 30 # 2 Kunal 28 -
Join conditions with & (and) or | (or). Each condition needs its own brackets.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara', 'Kabir'], 'Gender': ['F', 'M', 'F', 'M'], 'Marks': [88, 75, 93, 59]}) print(df[(df['Gender'] == 'F') & (df['Marks'] > 90)]) print(df[(df['Marks'] < 60) | (df['Marks'] > 90)]) # Output: # Name Gender Marks # 2 Sara F 93 # Name Gender Marks # 2 Sara F 93 # 3 Kabir M 59
DATAFRAME - ADD, DELETE & RENAME 8 programs
-
Assign a list to a new column name. The list must have one value per row.
import pandas as pd Genre = pd.DataFrame({'Type': ['Fiction', 'Non Fiction', 'Drama', 'Poetry'], 'Code': ['F', 'NF', 'D', 'P']}) Genre['Num_Copies'] = [300, 290, 450, 760] print(Genre) # Output: # Type Code Num_Copies # 0 Fiction F 300 # 1 Non Fiction NF 290 # 2 Drama D 450 # 3 Poetry P 760 -
df.loc[new_label] = [values in column order].
import pandas as pd StoreDF = pd.DataFrame({'Items': ['Bread', 'Milk', 'Eggs'], 'Quantity': [50, 100, 120], 'Unit_Price': [30, 25, 6]}) StoreDF.loc[3] = ['Butter', 40, 55] print(StoreDF) print(StoreDF['Items']) # Output: # Items Quantity Unit_Price # 0 Bread 50 30 # 1 Milk 100 25 # 2 Eggs 120 6 # 3 Butter 40 55 # 0 Bread # 1 Milk # 2 Eggs # 3 Butter # Name: Items, dtype: object -
rename(columns={old: new}) returns a new DataFrame.
import pandas as pd Genre = pd.DataFrame({'Type': ['Fiction', 'Drama'], 'Code': ['F', 'D']}) Genre = Genre.rename(columns={'Code': 'Book_Code'}) print(Genre) # Output: # Type Book_Code # 0 Fiction F # 1 Drama D -
drop(label) deletes a row; drop(name, axis=1) deletes a column.
import pandas as pd password = pd.DataFrame({ 'CodeName': ['aaaaaa', 'dragon', 'baseball', 'football', 'monkey', 'qwerty', 'abcde'], 'Category': ['alpha', 'animal', 'sport', 'sport', 'animal', 'alpha', 'alpha'], 'Frequency': [6.91, 18.52, 1.29, 11.11, 3.72, 1.85, 3.19]}) password.loc[len(password)] = ['abc123', 'alphanumeric', 12.8] # (i) add a row password = password.drop(2) # (ii) delete row 2 password = password.drop('Frequency', axis=1) # (iii) delete the column print(password) # Output: # CodeName Category # 0 aaaaaa alpha # 1 dragon animal # 3 football sport # 4 monkey animal # 5 qwerty alpha # 6 abcde alpha # 7 abc123 alphanumeric -
Three common changes to a DataFrame, one statement each.
import pandas as pd df = pd.DataFrame({'Name': ['Arpit', 'Vani', 'Chetan'], 'IP': [95, 89, 78], 'Maths': [88, 92, 80]}) df['Total'] = [183, 181, 158] # (i) add a column df.rename(columns={'Name': 'Student'}, inplace=True) # (ii) rename df.drop(columns=['Maths'], inplace=True) # (iii) delete a column print(df) # Output: # Student IP Total # 0 Arpit 95 183 # 1 Vani 89 181 # 2 Chetan 78 158 -
Print the first row, show one column, add a row, delete a column and rename a column.
import pandas as pd dF = pd.DataFrame({'PRODUCT_ID': ['P001', 'P002', 'P003'], 'PRODUCT_NAME': ['Laptop', 'Mobile', 'Chair'], 'CATEGORY': ['Electronics', 'Electronics', 'Furniture'], 'PRICE': [60000, 20000, 3000]}) print(dF.iloc[0]) # (i) first row print(dF['PRODUCT_NAME']) # (ii) one column dF.loc[3] = ['P006', 'AC', 'HOME', 80000] # (iii) add a row dF = dF.drop('CATEGORY', axis=1) # (iv) delete a column dF = dF.rename(columns={'PRODUCT_NAME': 'Item'}) # (v) rename a column print(dF) # Output: # PRODUCT_ID P001 # PRODUCT_NAME Laptop # CATEGORY Electronics # PRICE 60000 # Name: 0, dtype: object # 0 Laptop # 1 Mobile # 2 Chair # Name: PRODUCT_NAME, dtype: object # PRODUCT_ID Item PRICE # 0 P001 Laptop 60000 # 1 P002 Mobile 20000 # 2 P003 Chair 3000 # 3 P006 AC 80000 -
A new column can be calculated from other columns.
import pandas as pd df = pd.DataFrame({'Store': ['Store1', 'Store2', 'Store3'], 'Qtr1': [300, 350, 250], 'Qtr2': [240, 340, 180], 'Qtr3': [450, 403, 145], 'Qtr4': [230, 210, 160]}) df['Total_Sales'] = df['Qtr1'] + df['Qtr2'] + df['Qtr3'] + df['Qtr4'] df = df.drop(2) # delete the last row (label 2) print(df) # Output: # Store Qtr1 Qtr2 Qtr3 Qtr4 Total_Sales # 0 Store1 300 240 450 230 1220 # 1 Store2 350 340 403 210 1303 -
rename(index={old: new}) changes row labels; df.index = [...] replaces all of them.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara'], 'Marks': [88, 75, 93]}) df = df.rename(index={0: 'a', 1: 'b'}) print(df) df.index = ['x', 'y', 'z'] print(df) # Output: # Name Marks # a Riya 88 # b Aman 75 # 2 Sara 93 # Name Marks # x Riya 88 # y Aman 75 # z Sara 93
DATAFRAME - ITERATION & ANALYSIS 6 programs
-
iterrows() gives the row label and the row, one row at a time.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara'], 'Marks': [88, 75, 93]}) for label, row in df.iterrows(): print(label, row['Name'], row['Marks']) # Output: # 0 Riya 88 # 1 Aman 75 # 2 Sara 93 -
items() gives the column name and the column, one column at a time.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman'], 'Marks': [88, 75]}) for name, column in df.items(): print("Column:", name) print(column.values) # Output: # Column: Name # ['Riya' 'Aman'] # Column: Marks # [88 75] -
duplicated() marks repeated rows; drop_duplicates() removes them.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Riya', 'Sara'], 'Marks': [88, 75, 88, 93]}) print(df.duplicated()) print(df.drop_duplicates()) # Output: # 0 False # 1 False # 2 True # 3 False # dtype: bool # Name Marks # 0 Riya 88 # 1 Aman 75 # 3 Sara 93 -
sort_values() arranges rows; ascending=False gives highest first.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara', 'Kabir'], 'Marks': [88, 75, 93, 67]}) print(df.sort_values('Marks', ascending=False)) # Output: # Name Marks # 2 Sara 93 # 0 Riya 88 # 1 Aman 75 # 3 Kabir 67 -
Group the rows by category and print the total expenditure of each category.
import pandas as pd sales = pd.DataFrame({ 'Category': ['Stationery', 'Grocery', 'Stationery', 'Grocery', 'Electronics'], 'Item': ['Pen', 'Rice', 'Notebook', 'Oil', 'Earphones'], 'Expenditure': [500, 2000, 800, 1500, 1200]}) print(sales.groupby('Category')['Expenditure'].sum()) # Output: # Category # Electronics 1200 # Grocery 3500 # Stationery 1300 # Name: Expenditure, dtype: int64 -
Find the average, highest and lowest marks in each subject, and the topper.
import pandas as pd result = pd.DataFrame({'Name': ['Riya', 'Aman', 'Sara', 'Kabir'], 'English': [85, 72, 90, 64], 'Maths': [78, 95, 88, 70], 'IP': [92, 81, 97, 75]}) subjects = result[['English', 'Maths', 'IP']] print("Average:") print(subjects.mean()) print("Highest:") print(subjects.max()) result['Total'] = subjects.sum(axis=1) # axis=1: add across each row print(result) print("Topper:", result.loc[result['Total'].idxmax(), 'Name']) # Output: # Average: # English 77.75 # Maths 82.75 # IP 86.25 # dtype: float64 # Highest: # English 90 # Maths 95 # IP 97 # dtype: int64 # Name English Maths IP Total # 0 Riya 85 78 92 255 # 1 Aman 72 95 81 248 # 2 Sara 90 88 97 275 # 3 Kabir 64 70 75 209 # Topper: Sara
IMPORT & EXPORT CSV FILES 6 programs
-
to_csv() writes the DataFrame to a file. index=False leaves out the row numbers.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman'], 'Marks': [88, 75]}) df.to_csv('marks.csv', index=False) print(open('marks.csv').read()) # see what was written # Output: # Name,Marks # Riya,88 # Aman,75 -
The first line of the file becomes the column names.
import pandas as pd # make a small file to read open('customer.csv', 'w').write("Name,Age,City\nRudra,17,Kolkata\nDivya,19,Dehradun\nNabeel,22,Lucknow\n") DF = pd.read_csv('customer.csv') print(DF) print(DF.tail(2)) # the last two rows # Output: # Name Age City # 0 Rudra 17 Kolkata # 1 Divya 19 Dehradun # 2 Nabeel 22 Lucknow # Name Age City # 1 Divya 19 Dehradun # 2 Nabeel 22 Lucknow -
Error-finding question. Mistakes fixed: Pandas -> pandas, load_csv -> read_csv, sep="-" removed (values are separated by commas), data_frame -> df.
import pandas as pd open('data.csv', 'w').write("Item,Qty\nPen,10\nPencil,25\n") df = pd.read_csv('data.csv') print(df) # Output: # Item Qty # 0 Pen 10 # 1 Pencil 25 -
sep= tells pandas which character separates the values, e.g. ; or |.
import pandas as pd df = pd.DataFrame({'Name': ['Riya', 'Aman'], 'City': ['Delhi', 'Pune']}) df.to_csv('people.csv', sep=';', index=False) print(open('people.csv').read()) df2 = pd.read_csv('people.csv', sep=';') print(df2) # Output: # Name;City # Riya;Delhi # Aman;Pune # # Name City # 0 Riya Delhi # 1 Aman Pune -
header=None stops the first line being used as names; names= gives your own column names.
import pandas as pd open('scores.csv', 'w').write("Riya,88\nAman,75\nSara,93\n") df = pd.read_csv('scores.csv', header=None, names=['Name', 'Marks']) print(df) # Output: # Name Marks # 0 Riya 88 # 1 Aman 75 # 2 Sara 93 -
Read a file, keep the rows you need, and export them to another file.
import pandas as pd open('students.csv', 'w').write("Name,Marks\nRiya,88\nAman,35\nSara,93\nKabir,28\n") df = pd.read_csv('students.csv') passed = df[df['Marks'] >= 40] passed.to_csv('passed.csv', index=False) print(open('passed.csv').read()) # Output: # Name,Marks # Riya,88 # Sara,93
DATA VISUALIZATION - LINE PLOTS 5 programs
-
plt.plot(x, y) joins the points with a line; plt.show() displays it.
import matplotlib.pyplot as plt days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] temp = [30, 32, 31, 35, 33] plt.plot(days, temp) plt.show() -
Add a title and axis labels, and save the chart as a picture with savefig() before show().
import matplotlib.pyplot as plt months = ['April', 'May', 'June', 'July', 'August'] emission = [40, 50, 30, 60, 20] plt.plot(months, emission, marker='o') plt.title('Month wise CO2 emission') plt.xlabel('Month') plt.ylabel('Percentage') plt.savefig('emission.png') # save first ... plt.show() # ... then show -
label= names the line and plt.legend() shows that name on the chart.
import matplotlib.pyplot as plt months = ['Jan', 'Feb', 'Mar', 'Apr'] sales = [12000, 15000, 11000, 18000] plt.plot(months, sales, label="Sales") plt.title("Sales Performance") plt.xlabel("Month") plt.ylabel("Amount") plt.legend() plt.show() -
color=, linestyle= and marker= change how the line looks.
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 3, 5, 6] plt.plot(x, y, color='red', linestyle='dashed', marker='s', linewidth=2) plt.title('Styled Line') plt.grid(True) plt.show() -
Call plt.plot() twice; the legend tells the lines apart.
import matplotlib.pyplot as plt tests = ['Test 1', 'Test 2', 'Test 3', 'Test 4'] class_a = [65, 70, 78, 82] class_b = [60, 74, 72, 85] plt.plot(tests, class_a, marker='o', label='Class 12-A') plt.plot(tests, class_b, marker='o', label='Class 12-B') plt.title('Average Marks in Unit Tests') plt.xlabel('Test') plt.ylabel('Average Marks') plt.legend() plt.show()
DATA VISUALIZATION - BAR GRAPHS 5 programs
-
plt.bar(x, heights) draws one bar for each item.
import matplotlib.pyplot as plt Fruits = ['Apple', 'Guava', 'Papaya', 'Grapes', 'Mango'] Price = [150, 70, 50, 30, 120] plt.bar(Fruits, Price) plt.title('Price of Fruits') plt.xlabel('Fruits') plt.ylabel('Price (Rs)') plt.savefig('fruits.png') plt.show() -
A bar chart with title, axis labels and savefig().
import matplotlib.pyplot as plt hobby = ['Dance', 'Music', 'Painting', 'Playing Sports'] people = [300, 400, 100, 500] plt.bar(hobby, people) plt.title('Favourite Hobby') plt.xlabel('Hobbies') plt.ylabel('Number of people') plt.savefig('hobbies.png') plt.show() -
color= and width= change the bars; plt.barh() draws them sideways.
import matplotlib.pyplot as plt subjects = ['English', 'Maths', 'IP', 'Economics'] marks = [85, 78, 95, 70] plt.bar(subjects, marks, color=['red', 'green', 'blue', 'orange'], width=0.5) plt.title('Marks of Riya') plt.show() plt.barh(subjects, marks, color='teal') plt.title('Same Marks, Horizontal Bars') plt.show() -
Calculate averages with pandas, then plot them with title and legend.
import pandas as pd import matplotlib.pyplot as plt result = pd.DataFrame({'English': [85, 72, 90, 64], 'Maths': [78, 95, 88, 70], 'IP': [92, 81, 97, 75]}) avg = result.mean() plt.bar(avg.index, avg.values, label='Average marks') plt.title('Subject-wise Average Marks') plt.xlabel('Subject') plt.ylabel('Average') plt.legend() plt.show() -
Shift the second set of bars a little to the right so both are visible.
import matplotlib.pyplot as plt import numpy as np subjects = ['English', 'Maths', 'IP'] boys = [72, 80, 85] girls = [78, 76, 90] x = np.arange(len(subjects)) # 0, 1, 2 plt.bar(x, boys, width=0.4, label='Boys') plt.bar(x + 0.4, girls, width=0.4, label='Girls') plt.xticks(x + 0.2, subjects) # subject names under the pairs plt.title('Average Marks: Boys vs Girls') plt.legend() plt.show()
DATA VISUALIZATION - HISTOGRAMS 3 programs
-
A histogram shows how many values fall in each range (bin).
import matplotlib.pyplot as plt Height_cms = [145, 141, 142, 142, 143, 144, 141, 140, 143, 144] plt.hist(Height_cms) plt.title('Height of Students') plt.xlabel('Height (cm)') plt.ylabel('Number of students') plt.savefig('heights.png') plt.show() -
bins= sets the ranges; edgecolor= outlines the bars.
import matplotlib.pyplot as plt Ages = [22, 25, 24, 28, 30, 24, 29, 27, 21, 23] binsize = [20, 22, 24, 26, 28, 30] plt.hist(Ages, bins=binsize, edgecolor='black', label='Participants') plt.xlabel('Age') plt.ylabel('Number of Participants') plt.title("Age Distribution") plt.legend() plt.show() -
Use bins for grade ranges to see how many students got each grade band.
import matplotlib.pyplot as plt marks = [35, 42, 58, 61, 67, 72, 75, 78, 81, 84, 88, 91, 95, 66, 54] plt.hist(marks, bins=[33, 50, 60, 75, 90, 100], color='orange', edgecolor='black') plt.title('Marks Distribution of Class 12') plt.xlabel('Marks') plt.ylabel('Number of students') plt.show()