0% found this document useful (0 votes)
36 views66 pages

Ip File

Ip file class 12

Uploaded by

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

Ip File

Ip file class 12

Uploaded by

preeti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

PRACTICALS

Data HanDling
PRACTICAL 01
Problem statement: Create a Series object using the Python
sequence with 5 elements.
Solution:
Source code:
import pandas as pd
L = [21, 34, 47, 58, 67]
S = pd.Series(L)
print(S)
OUTPUT:
PRACTICAL 02
Problem statement: Create a Series object using ndarray that has 5
elements in the range 60 and 120.
Solution:
Source Code:
import pandas as pd
import numpy as np
S = pd.Series(np.arange(60, 110, 10)) # Changed range
print(S)
OUTPUT:
PRACTICAL 03
Problem statement: Create a Series object using a dictionary that
stores the number of students in each section of class 12th in your
school.
Solution:
Source Code:
import pandas as pd
D = {'A': 28, 'B': 31, 'C': 33, 'D': 45, 'E': 50} # Modified number of
students
S = pd.Series(D)
print(S)
OUTPUT:
PRACTICAL 04
Problem statement: Create a Series object ‘Item’ that stores the rate
of each product as given below:
• Soap: 65
• Salt: 22
• Sugar: 45
Write code to modify the rate of soap to 55 and sugar to 50. Print the
changed rates.
Solution:
Source code:
import pandas as pd
S = pd.Series([65, 22, 45], ['soap', 'salt', 'sugar']) # Modified rates
print(S)

S['soap'] = 55 # Update soap price


S['sugar'] = 50 # Update sugar price
print("\nAfter Updating values:")
print(S)
OUTPUT:
Practical 05
Problem statement: Number of students in class 11 and class 12 in
three streams (Science, Commerce, and Humanities) are stored in
two Series objects class11 and class12. Write code to find the total
number of students in class 11 & class 12, stream-wise.
Solution:
Source Code:
import pandas as pd
D1 = {'Science': 32, 'Commerce': 36, 'Humanities': 25} # Updated
values
D2 = {'Science': 30, 'Commerce': 38, 'Humanities': 28} # Updated
values
Class11 = pd.Series(D1)
Class12 = pd.Series(D2)
print("Class 11:\n", Class11)
print("Class 12:\n", Class12)
print("\nTotal Students (Stream-wise):")
print(Class11 + Class12)
IMAGE:
OUTPUT:
Practical 06
Problem statement: Create a Series temp that stores the
temperature of seven days in it. The index should be ‘Sunday’,
‘Monday’, etc.
Solution:
Source Code:
import pandas as pd
temp = pd.Series([47, 45, 44, 43, 42, 41, 40],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday']) # Modified temperatures
print(temp)
print("\nTemp of first three days:\n", temp.head(3))
print("\nTemp of last three days:\n", temp.tail(3))
print("\nTemp in reverse order:\n", temp[::-1])
print("\nTemp from Tuesday to Friday:\n", temp['Tuesday':'Friday'])
print("\nSquare of all Temperatures:\n", temp * temp)
OUTPUT:
Practical 07
Problem statement: Create a Series object employee that stores the salary of 7
employees. Write a script to print:
1. Total number of elements
2. Whether the series is empty or not
3. Whether the series contains NaN values or not
4. Count non-NA elements
5. Axis labels
Solution:
Source Code:
import pandas as pd
D = {'Ram': 40000, 'Hari': 50000, 'Suman': 30000, 'Chandan': 45000, 'Raghu':
32000} # Changed values
employee = pd.Series(D)
print(employee)
print("\nTotal number of employees:", employee.size)
if employee.empty:
print("Series is empty")
else:
print("Series is not empty")
if employee.hasnans:
print("Series contains NaN elements")
else:
print("Series does not contain NaN elements")
print("Total number of non-NA elements:", employee.count())
print("Axis labels:", employee.axes)
OUTPUT:
Practical 08
Problem statement: Create the following dataframe Sport containing
sport-wise marks for five students. Use a 2D dictionary to create the
dataframe.
Student Sport Marks

Jai Cricket 75

Raj Football 85

John Tennis 89

Karan Kabaddi 90

Chandu Hockey 93
Solution:
Source Code:
import pandas as pd
D = {'student': ['Jai', 'Raj', 'John', 'Karan', 'Chandu'],
'sport': ['Cricket', 'Football', 'Tennis', 'Kabaddi', 'Hockey'],
'marks': [75, 85, 89, 90, 93]} # Changed values
sport = pd.DataFrame(D, ['I', 'II', 'III', 'IV', 'V'])
print(sport)
OUTPUT:
Practical 09
Problem statement: Create a dataframe from a list containing
dictionaries of the most economical bikes with their name and rate of
three companies. The company name should be the row labels.
Solution:
Source Code:
import pandas as pd
L1 = {'Name': 'Platina', 'Cost': 70000} # Modified bike name and cost
L2 = {'Name': 'Splendor', 'Cost': 65000}
L3 = {'Name': 'CT100', 'Cost': 60000}
Bike = [L1, L2, L3]
df = pd.DataFrame(Bike, ['Bajaj', 'Hero', 'TVS'])
print(df)
OUTPUT:
Practical 10
Problem statement: Create the following dataframe sales containing year-wise sales figures for five
salespersons in INR. Use the year as column labels, and salesperson names as row labels.

2014 2015 2016 2017


madhu 1500 2300 3100 4000
kusum 1800 2400 3500 5000
kinshuk 2200 2900 4500 6000
ankit 3200 4100 5500 7000
shruti 3800 4600 6200 8000

Solution:

Source Code:

import pandas as pd

D = {2014: [1500, 1800, 2200, 3200, 3800],

2015: [2300, 2400, 2900, 4100, 4600],

2016: [3100, 3500, 4500, 5500, 6200],

2017: [4000, 5000, 6000, 7000, 8000]} # Changed sales figures

sales = pd.DataFrame(D, ['Madhu', 'Kusum', 'Kinshuk', 'Ankit', 'Shruti'])

print("----DataFrame----")

print(sales)

print("\n----Row Labels----")

print(sales.index)

print("\n----Column Labels----")

print(sales.columns)

print("\n----Bottom two Rows----")

print(sales.tail(2))

print("\n----Top two Rows----")

print(sales.head(2))
OUTPUT:

.
Practical 11
Problem statement: Create a dataframe cloth as given below and write a program to:

1. Check if cloth is empty or not.

2. Change cloth such that it becomes its transpose.

3. Display the number of rows and columns of cloth.

4. Count and display non-NA values for each column.

5. Count and display non-NA values for each row.

CName Size Price


Jeans L 1300
Shirt XL 900
Trouser M 1200
T-Shirt XL 800
Jacket M 2000
Solution:

Source Code:

import pandas as pd

D = {'CName': ['Jeans', 'Shirt', 'Trouser', 'T-Shirt', 'Jacket'],

'Size': ['L', 'XL', 'M', 'XL', 'M'],

'Price': [1300, 900, 1200, 800, 2000]} # Changed values

cloth = pd.DataFrame(D)

print("----Dataframe----")

print(cloth)

print("----Checking if dataframe is empty or not----")

if cloth.empty:

print("Cloth is Empty")

else:

print("Cloth is not Empty")

print("\n----Transpose Dataframe----")

print(cloth.T)

print("\n----Total number of rows and columns----")

print(cloth.shape)

print("\n----Number of non-NA elements in each column----")

print(cloth.count())

print("\n----Number of non-NA elements in each row----")

print(cloth.count(axis=1))
OUTPUT:
Practical 12
Problem statement: Create a dataframe cloth and perform the following operations:

1. Change the name of ‘Trouser’ to ‘Pant’ and ‘Jeans’ to ‘Denim’.

2. Increase the price of all cloth by 10%.

3. Rename all the indexes to [C001, C002, C003, C004, C005].

4. Delete the data of C003 from the cloth.

5. Delete the size column from cloth.

Solution:

Source code:

import pandas as pd

D = {'CName': ['Jeans', 'Shirt', 'Trouser', 'T-Shirt', 'Jacket'],

'Size': ['L', 'XL', 'M', 'XL', 'M'],

'Price': [1300, 900, 1200, 800, 2000]} # Changed values

cloth = pd.DataFrame(D, ['C1', 'C2', 'C3', 'C4', 'C5'])

print("----Dataframe----")

print(cloth)

print("\n----Change name of Trouser to Pant and Jeans to Denim----")

cloth.at['C3', 'CName'] = 'Pant'

cloth.at['C1', 'CName'] = 'Denim'

print(cloth)

print("\n----Increase price of all cloth by 10%----")

cloth['Price'] = cloth['Price'] + (cloth['Price'] * 10 / 100)

print(cloth)

print("\n----Rename all the indexes to [C001,C002,C003,C004,C005]----")

cloth.rename(index={'C1': 'C001', 'C2': 'C002', 'C3': 'C003', 'C4': 'C004', 'C5': 'C005'}, inplace=True)

print(cloth)

print("\n----Delete the data of C003----")

cloth = cloth.drop(['C003'])

print(cloth)

print("\n----Delete column 'Size'----")

del cloth['Size']

print(cloth)
OUTPUT:
Practical 13
Problem statement: Create a dataframe aid as given below and write a program to:
1. Display the books and shoes only.
2. Display toys only.
3. Display quantity in MP and CG for toys and books.
4. Display the quantity of books in AP.

Toys Books Shoes


MP 7000 4200 5500
UP 3400 3300 1200
AP 8200 5600 3700
CG 4500 2100 3200

Solution:
Source code:
import pandas as pd
D = {'Toys': {'MP': 7000, 'UP': 3400, 'AP': 8200, 'CG': 4500},
'Books': {'MP': 4200, 'UP': 3300, 'AP': 5600, 'CG': 2100},
'Shoes': {'MP': 5500, 'UP': 1200, 'AP': 3700, 'CG': 3200}} # Changed values
aid = pd.DataFrame(D)
print("----DataFrame----")
print(aid)
print("\n----Display the books and shoes only----")
print(aid[['Books', 'Shoes']])
print("\n----Display toys only----")
print(aid['Toys'])
print("\n----Display quantity in MP and CG for toys and books----")
print(aid.loc[['MP', 'CG'], ['Toys', 'Books']])
print("\n----Display quantity of books in AP----")
print(aid.at['AP', 'Books'])
OUTPUT:
Practical 14
Problem statement: Create a dataframe aid as given below and write
a program to save the values of aid to a comma-separated file
aidfigures.csv on the disk. Do not write the row and column labels.
Toys Books Shoes
MP 7200 4200 5500
UP 3400 3300 1200
AP 8200 5600 3700
CG 4500 2100 3200
Solution:
Source code:
import pandas as pd
D = {'Toys': {'MP': 7000, 'UP': 3400, 'AP': 8200, 'CG': 4500},
'Books': {'MP': 4200, 'UP': 3300, 'AP': 5600, 'CG': 2100},
'Shoes': {'MP': 5500, 'UP': 1200, 'AP': 3700, 'CG': 3200}} # Changed
values
aid = pd.DataFrame(D)
print(aid)
aid.to_csv('aidfigures.csv', header=False, index=False)
IMAGE:

Output: The output is the CSV file saved as aidfigures.csv without


row and column labels.
Practical 15
Problem statement: Read the data in the file aidfigures.csv into a
dataframe aidretrieved and display it. Now update the row labels and
column labels of aidretrieved to match that of aid from practical 19.
Solution:
Source code:
import pandas as pd
aidretrieved = pd.read_csv('aidfigures.csv', names=['Toys', 'Books',
'Shoes']) # Changed path to file
aidretrieved.index = ['MP', 'UP', 'AP', 'CG']
print(aidretrieved)
OUTPUT:
Practical 16
Problem statement: Collect and store the total medals won by 10
countries in the Olympic games and represent it in the form of a bar
chart with a title to compare and analyze the data.
Solution:
Source code:
import matplotlib.pyplot as plt
medals = [100, 120, 90, 70, 85, 110, 95, 60, 50, 45] # Changed values
countries = ['USA', 'China', 'Russia', 'India', 'UK', 'Germany', 'Japan',
'France', 'Canada', 'Italy']
plt.bar(countries, medals)
plt.title('Olympics Medal Tally')
plt.ylabel('Total Medals')
plt.show()
OUTPUT:
Image:
Practical 17
Problem statement: Create a multiple line chart to analyze the sales
of different bikes across months.
Jan Feb March April May June
Honda 25 45 110 85 92 105
Suzuki 35 58 77 62 55 34
TVS 95 81 87 66 78 102
Solution:
Source Code:
import matplotlib.pyplot as plt
month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
honda = [25, 45, 110, 85, 92, 105] # Changed values
suzuki = [35, 58, 77, 62, 55, 34] # Changed values
tvs = [95, 81, 87, 66, 78, 102] # Changed values
plt.plot(month, honda, label='Honda')
plt.plot(month, suzuki, label='Suzuki')
plt.plot(month, tvs, label='TVS')
plt.title('Bike Sales Analysis')
plt.xlabel('Months')
plt.ylabel('Number of Bikes Sold')
plt.legend(loc='lower center')
plt.show()
OUTPUT:
Practical 18
Problem statement: Given the school result data, analyze the performance of
the student on different parameters, e.g., subject-wise or class-wise. Create a
dataframe and plot appropriate charts.
class eng math phy chem it
9 80 89 75 90 93
10 87 90 82 95 99
11 89 78 80 85 94
12 91 96 88 92 100
Solution:
Source code:
import pandas as pd
import matplotlib.pyplot as plt
data = {'Eng': [80, 87, 89, 91],
'Math': [89, 90, 78, 96],
'Phy': [75, 82, 80, 88],
'Chem': [90, 95, 85, 92],
'IT': [93, 99, 94, 100]} # Changed values
df = pd.DataFrame(data, [9, 10, 11, 12])
# Class-wise Marks Analysis
df.plot(kind='bar', title='Class Wise Marks Analysis', xlabel='Class',
ylabel='Marks')
# Subject-wise Marks Analysis
df.T.plot(kind='bar', title='Subject Wise Marks Analysis', xlabel='Subjects',
ylabel='Marks')
plt.legend(loc='lower center')
plt.show()
OUTPUT:
Practical 19
Problem statement: The following seat bookings are the daily
records of a month at PVR cinemas. Construct a histogram from the
data with 10 bins.
| Seats | 124, 124, 135, 145, 165, 180, 190, 150, 158, 142, 143, 124,
145, 150, 200, 142, 130, 189, 200, 130, 170, 200, 145, 143, 156, 142,
130, 200, 189, 170 |
Solution:
Source code:
import matplotlib.pyplot as plt
bookings = [124, 124, 135, 145, 165, 180, 190, 150, 158, 142, 143,
124, 145, 150, 200, 142, 130, 189, 200, 130, 170, 200, 145, 143, 156,
142, 130, 200, 189, 170] # Changed values
plt.hist(bookings, bins=10)
plt.title("Booking Records @ PVR")
plt.xlabel("Seats Booked")
plt.ylabel("Frequency")
plt.show()
OUTPUT:
MY SQL
PRaCtiCalS
PRACTICAL 20:
Problem statement: Create a student table with the student id,
name, and marks as attributes where the student id is the primary
key.
SOLUTION:
Source Code:
PRACTICAL 21:
Problem statement: In the table ‘student’ created in practical 26,
insert the details of new students.
SOLUTION:
Source Code:
PRACTICAL 22:
Problem statement: Write SQL command to get the details of the
students with marks more than 80.
SOLUTION:
Source Code :
PRACTICAL 23:
Problem statement: Write SQL command to Find the min, max, sum,
and average of the marks in a student marks table..
SOLUTION:
Source Code:
PRACTICAL 24:
Problem statement: Delete the details of a student table created in
Practical 21.
SOLUTION:
Source Code:
PRACTICAL 25:
Problem statement: Find the total number of customers from
each country in the table (customer ID, customer Name,
country) using group by.

SOLUTION:
Source Code:
PRACTICAL 26:
Problem statement: Write a SQL query to order the (student
ID, marks) table in descending order of the marks.
SOLUTION:
Source Code:
PRACTICAL 27:
Problem statement: for the given table ‘Hospital’ write SQL command
to display name all patient admitted in month of May.

SOLUTION:
Source Code:
PRACTICAL 28:
Problem statement: for the given table ‘Hospital’ write SQL
command to Display patient name in upper case with year of
admission.

SOLUTION:
Source Code:
PRACTICAL 29:
Problem statement: for the given table ‘Hospital’ Create sql query to
display first four letters of the patient name along with length of their
name who admitted before may.

SOLUTION:
Source Code:
AGGREGATE
FUNCTIONS
PRACTICALS :
PRACTICAL 30:

Problem Statement : Create table student .


SOLUTION:
Source Code:
USE mancy;
CREATE TABLE students (
s_no INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
dob DATE,
gender ENUM('Male', 'Female', 'Other'),
marks DECIMAL(5, 2),
mobile_no VARCHAR(15),
stream VARCHAR(50)
);

Insert Values:
INSERT INTO students (name, dob, gender, marks, mobile_no,
stream)
VALUES
('Alice', '2003-04-15', 'Female', 85.50, '9876543210', 'Science'),
('Bob', '2002-07-22', 'Male', 78.75, '9123456780', 'Commerce'),
('Charlie', '2003-01-10', 'Male', 92.00, '9988776655', 'Arts'),
('Daisy', '2002-12-05', 'Female', 88.25, '8765432109', 'Science'),
('Eve', '2003-05-17', 'Female', 95.00, '7654321098', 'Commerce'),
('Frank', '2002-08-30', 'Male', 70.00, '6543210987', 'Arts'),
('Grace', '2003-11-11', 'Other', 89.50, '5432109876', 'Science'),
('Hank', '2002-09-25', 'Male', 82.00, '4321098765', 'Commerce');
PRACTICAL 31:
Problem Statement: Calculate the total marks obtained by all
students in the students table.
SOLUTION:
Source Code:
PRACTICAL 32:
Problem Statement: Determine the average marks obtained by
students in the students table. This average will provide insights into
the general performance level of the student population.
SOLUTION:
Source Code:
PRACTICAL 33:
Problem Statement: Compute the average marks of
students who scored less than 90. This analysis aims to
understand the performance of students who may
need additional support or improvement.
SOLUTION:
Source Code:
PRACTICAL 34:
Problem Statement: Identify the highest marks
achieved by any student in the students table. This will
highlight the top performer and set a benchmark for
others.
SOLUTION:
PRACTICAL 35:
Problem Statement: Find the lowest marks obtained by any
student in the students table. This information is crucial for
recognizing students who may require extra assistance.
SOLUTION:
Source Code:
PRACTICAL 36:
Problem Statement: Calculate the total number of
students enrolled in the students table. This count will
provide essential demographic information for further
analysis.
SOLUTION :
Source Code:
PRACTICAL 37:
Problem Statement: Retrieve the list of students sorted
by their marks in descending order. This sorting will
facilitate quick identification of high achievers.
SOLUTION:
Source Code:
PRACTICAL 38:
Problem Statement: Generate a list of students sorted first by
their stream and then by their marks in descending order.
This will allow for a comparative analysis of performance
across different streams.
SOLUTION:
Source Code:
PRACTICAL 39:
Problem Statement: Retrieve students’ names and
their marks, sorting the results by marks using an alias
for clarity. This provides a clean and organized view of
student performance.
SOLUTION:
Source Code:
PRACTICAL 40:
Problem Statement: Calculate the average marks for each
stream in the students table. This grouping will help identify
which streams are performing well and which may need
curricular improvements.
SOLUTION:
Source Code:
PRACTICAL 41:
Problem Statement: List streams with an average mark greater
than 80. This query will highlight streams that are performing
above the average threshold and may require fewer
interventions.
SOLUTION:
Source Code:
PRACTICAL 42:
Problem Statement: Determine the number of distinct
streams present in the students table. This will provide
insights into the diversity of academic programs within the
institution.
SOLUTION:
Source Code:
BIBLIOGRAPHY:
References and Bibliography:
• Informatics Practices Class-XII NCERT Publication
• Informatics Practices Class-XII by Sumita Arora
• Think Python by Allen B Downey
• Python for everybody by Charles Severance
• Learning MYSQL by Seyed M. M. Tahaghoghi
• MySQL in a nutshell by Russell J. T. Dyer
• www.geeksforgeeks.org
• www.ncert.co.in
• www.techtipnow.in

You might also like