0% found this document useful (0 votes)
56 views27 pages

Practical

The document contains practical file questions for Class XII Informatics Practices at Kalka Public School, detailing various Python programming tasks involving the creation and manipulation of Series and DataFrames using the pandas library. It includes tasks such as filtering data, performing arithmetic operations, and visualizing data with Matplotlib. Each task is accompanied by example code snippets demonstrating the required functionality.

Uploaded by

Farhan Sheikh
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)
56 views27 pages

Practical

The document contains practical file questions for Class XII Informatics Practices at Kalka Public School, detailing various Python programming tasks involving the creation and manipulation of Series and DataFrames using the pandas library. It includes tasks such as filtering data, performing arithmetic operations, and visualizing data with Matplotlib. Each task is accompanied by example code snippets demonstrating the required functionality.

Uploaded by

Farhan Sheikh
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/ 27

KALKA PUBLIC SCHOOL, ALAKNANDA

Practical File Questions


Class XII 2024-25
Subject: Informatics Practices
Name :
Class :
Section :
Roll NO :

SERIES

1. To write a Python program to create a Series to store 5 students Percentage Using


dictionary and print all the elements that are above 75 percent.
import pandas as pd

# Create a Series
data = {"Amit": 76, "Rita": 82, "John": 65, "Sara": 89, "Rohan": 74}
percentages = pd.Series(data)

# Filter and print values above 75%


print("Students with percentages above 75%:")
print(percentages[percentages > 75])

2. To write a Python program to create a Series object that stores the Initial budget
allocated (50000/- each) for the four quarters of the year: Qtr1, Qtr2, Qtr3 and Qtr4.
import pandas as pd

# Create a Series for quarterly budget


quarters = pd.Series([50000, 50000, 50000, 50000], index=["Qtr1", "Qtr2",
"Qtr3", "Qtr4"])

# Print the Series


print("Budget for each quarter:")
print(quarters)
3. To write a Python program to create a Series object that stores the Employee names
as index and their Salary as values.
import pandas as pd

# Create a Series for employees and their salaries


employees = pd.Series([30000, 40000, 35000], index=["Amit", "Rita", "John"])

# Print the Series


print("Employee Salaries:")
print(employees)

4. To Write a Python program to create a Series object with Employee names as the
index and their salaries as values. Accept the name of the employee whose salary needs
to be changed, along with the new salary, and update it in the Series.
import pandas as pd

# Create a Series for employees and their salaries


employees = pd.Series([30000, 40000, 35000], index=["Amit", "Rita", "John"])

# Input the employee name and new salary


name = input("Enter the employee name to update salary: ")
new_salary = int(input("Enter the new salary: "))

# Update the salary in the Series


employees[name] = new_salary

# Print updated Series


print("Updated Employee Salaries:")
print(employees)
5. To create a program in python to perform following mathematical Operations on Two
Series objects: (i) Addition (ii) Subtraction
(iii) Multiplication (iv) Division
import pandas as pd

# Create two Series


s1 = pd.Series([10, 20, 30], index=["a", "b", "c"])
s2 = pd.Series([5, 10, 15], index=["a", "b", "c"])

# Perform arithmetic operations


print("Addition:\n", s1 + s2)
print("Subtraction:\n", s1 - s2)
print("Multiplication:\n", s1 * s2)
print("Division:\n", s1 / s2)

6. To write a Python program to create two series i.e. population and average income of
Four Zones, and then calculate per capita income storing in third pandas series print it.
import pandas as pd

# Create two Series for population and average income


population = pd.Series([1000000, 800000, 1200000, 950000], index=["North",
"South", "East", "West"])
avg_income = pd.Series([20000, 25000, 18000, 22000], index=["North", "South",
"East", "West"])

# Calculate per capita income


per_capita_income = avg_income / population

# Print the result


print("Per Capita Income for each zone:")
print(per_capita_income)

7. To write a Python program to create a Series using list and display the following
attributes of the Series: (i) index (ii) dtype (iii) size (iv) shape (v) hasnans
import pandas as pd

# Create a Series using a list


marks = pd.Series([85, 90, 78, 88, 92])

# Display attributes of the Series


print("Index:", marks.index)
print("Data Type:", marks.dtype)
print("Size:", marks.size)
print("Shape:", marks.shape)
print("Has NaN values:", marks.hasnans)
8. To write a Python program to create a Series using list of Marks of 10 students and
display first 5 Students’ marks and Last 2 Students’ marks from Series object.
import pandas as pd

# Create a Series using a list


marks = pd.Series([85, 90, 78, 88, 92, 76, 89, 95, 84, 81])

# Display first 5 and last 2 marks


print("First 5 students' marks:")
print(marks.head(5))

print("Last 2 students' marks:")


print(marks.tail(2))

DATAFRAME

9. To write a Python program to create a panda’s Dataframe for the following table
Using Nested list

import pandas as pd
# Create a nested list for the data
data = [
["Stu1", "Arun", 21],
["Stu2", "Bala", 23],
["Stu3", "Charan", 22],
]

# Define column names


columns = ["ID", "Name", "Age"]

# Create a DataFrame
df = pd.DataFrame(data, columns=columns)

# Display the DataFrame


print("DataFrame:")
print(df)

10. To write a Python program to create a panda’s DataFrame called DF for the
following table Using Dictionary of List and perform the following operations:

(i) To Display only column 'Toys' from DataFrame DF.


(ii) To Display the row details of 'AP' and 'OD' from DataFrame DF.
(iii) To Display the column 'Books' and 'Uniform' for 'M.P' and 'U.P' from DataFrame DF.
(iv) To Display consecutive 3 rows and 3 columns from DataFrame DF.
import pandas as pd
# Create a dictionary of lists for the data
data = {
"Toys": [7916, 8508, 7226, 7617],
"Books": [61896, 8208, 6149, 6157],
"Uniform": [610, 508, 611, 457],
"Shoes": [8810, 6798, 9611, 6457],
}

# Create the DataFrame with states as the index


DF = pd.DataFrame(data, index=["AP", "OD", "M.P", "U.P"])

# Display the DataFrame


print("Original DataFrame:")
print(DF)

# (i) Display only column 'Toys'


print("\nColumn 'Toys':")
print(DF["Toys"])

# (ii) Display the row details of 'AP' and 'OD'


print("\nRow details of 'AP' and 'OD':")
print(DF.loc[["AP", "OD"]])

# (iii) Display the columns 'Books' and 'Uniform' for 'M.P' and 'U.P'
print("\n'Books' and 'Uniform' for 'M.P' and 'U.P':")
print(DF.loc[["M.P", "U.P"], ["Books", "Uniform"]])

# (iv) Display consecutive 3 rows and 3 columns


print("\nConsecutive 3 rows and 3 columns:")
print(DF.iloc[:3, :3])
11. To write a Python program to create a panda’s DataFrame called DF for the
following table Using Dictionary of List and perform the following operations:

(i) Insert a new column “Bags” with values as [5891, 8628, 9785, 4475].
(ii) Delete the row details of M.P from DataFrame DF.

import pandas as pd

# Create a DataFrame using a dictionary of lists


data = {
"Toys": [7916, 8508, 7226, 7617],
"Books": [61896, 8208, 6149, 6157],
"Uniform": [610, 508, 611, 457],
"Shoes": [8810, 6798, 9611, 6457],
}
index_labels = ["AP", "OD", "M.P", "U.P"]

# Create the DataFrame


DF = pd.DataFrame(data, index=index_labels)
print("Original DataFrame:")
print(DF)

# (i) Insert a new column "Bags"


DF["Bags"] = [5891, 8628, 9785, 4475]
print("\nDataFrame after adding 'Bags' column:")
print(DF)

# (ii) Delete the row details of M.P


DF = DF.drop("M.P")
print("\nDataFrame after deleting the row of 'M.P':")
print(DF)

12. To write a Python program to create a pandas DataFrame to analyze number of


Government and Private medical college and their Total seats,Fees state wise details
using the dataset available at www.data.gov.in. Also, perform the following operations.
(i) To Change the name of the state AP to Andhra.
(ii) To Count and Display Non-NaN values of each column.
(iii) To Count and Display Non-NaN values of each row.
(iv) To Increase the fees of all colleges by 5%
(v) To Replace all NaN values with 0.
import pandas as pd

# Sample dataset for demonstration


data = {
"State": ["AP", "UP", "TN", "MH", "KA"],
"Govt_Colleges": [12, 15, 10, 20, 18],
"Private_Colleges": [8, 25, 30, 22, 25],
"Total_Seats": [5000, 7000, 10000, 12000, 9000],
"Fees": [100000, 150000, 200000, 250000, None],
}

# Create a DataFrame
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)

# (i) Change the name of the state AP to Andhra


df["State"] = df["State"].replace("AP", "Andhra")
print("\nAfter renaming 'AP' to 'Andhra':")
print(df)

# (ii) Count and display Non-NaN values of each column


non_nan_columns = df.count()
print("\nNon-NaN values in each column:")
print(non_nan_columns)

# (iii) Count and display Non-NaN values of each row


non_nan_rows = df.count(axis=1)
print("\nNon-NaN values in each row:")
print(non_nan_rows)

# (iv) Increase the fees of all colleges by 5%


df["Fees"] = df["Fees"] * 1.05
print("\nAfter increasing fees by 5%:")
print(df)

# (v) Replace all NaN values with 0


df = df.fillna(0)
print("\nAfter replacing NaN values with 0:")
print(df)
13. To write a Python program to create a panda’s DataFrame called DF for the
following table using Dictionary of List and display the details of students whose
Percentage is more than 85.

import pandas as pd

# Create a dictionary of lists for the data


data = {
"Stu_Name": ["Anu", "Arun", "Bala", "Charan", "Mano"],
"Degree": ["MBA", "MCA", "M.E", "M.Sc", "MCA"],
"Percentage": [90, 85, 91, 76, 84],
}

# Create a DataFrame using the dictionary


df = pd.DataFrame(data)

# Display the DataFrame


print("Original DataFrame:")
print(df)

# Filter and display details of students with percentage greater than 85


filtered_df = df[df["Percentage"] > 85]
print("\nStudents with Percentage greater than 85:")
print(filtered_df)

14. To write a Python program to create a DataFrame using Dictionary of list and
display the following attributes of the DataFrame: (i) index (ii) columns (iii) axes (iv)
dtypes (v) shape (vi) dimension (vii) T
import pandas as pd

# Create a dictionary of lists


data = {
"Stu_Name": ["Anu", "Arun", "Bala", "Charan", "Mano"],
"Degree": ["MBA", "MCA", "M.E", "M.Sc", "MCA"],
"Percentage": [90, 85, 91, 76, 84]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Display the DataFrame


print("DataFrame:")
print(df)

# Display the requested attributes


print("\n(i) Index:")
print(df.index)

print("\n(ii) Columns:")
print(df.columns)

print("\n(iii) Axes:")
print(df.axes)

print("\n(iv) Dtypes:")
print(df.dtypes)

print("\n(v) Shape:")
print(df.shape)

print("\n(vi) Dimension:")
print(df.ndim)

print("\n(vii) Transpose (T):")


print(df.T)
15. To write a Python program to create a panda’s DataFrame called Students for the
following table and demonstrate iterrows and iteritems.
import pandas as pd

# Creating the DataFrame


data = {
"Stu_ID": ["S1", "S2", "S3", "S4", "S5"],
"Stu_Name": ["Anu", "Arun", "Bala", "Charan", "Mano"],
"Percentage": [90, 85, 91, 76, 84],
}

students_df = pd.DataFrame(data)

# Displaying the DataFrame


print("Original DataFrame:")
print(students_df)

# Demonstrating iterrows() to iterate over rows


print("\nDemonstrating iterrows() (Row-wise iteration):")
for index, row in students_df.iterrows():
print(f"Row {index}: {row['Stu_Name']} scored {row['Percentage']}")

# Demonstrating iteritems() to iterate over columns


print("\nDemonstrating iteritems() (Column-wise iteration):")
for column, value in students_df.iteritems():
print(f"Column {column}:")
print(value)

16. To Write a Python program to store the details of Employess’ such as Empno,
Name, Salary into a Employee.csv file. Also, write a code to read employee details from
csv file.
import pandas as pd

# Data for employees


employee_data = {
"Empno": [101, 102, 103, 104],
"Name": ["John", "Alice", "Bob", "Charlie"],
"Salary": [50000, 60000, 55000, 65000],
}

# Creating DataFrame
employees_df = pd.DataFrame(employee_data)

# Writing the DataFrame to a CSV file


employees_df.to_csv("Employee.csv", index=False)

# Reading the data back from the CSV file


read_employee_df = pd.read_csv("Employee.csv")

# Displaying the data from the CSV file


print("Employee details read from the Employee.csv file:")
print(read_employee_df)

Matplotlib – Data Visualization

17. To write a Python program to plot a Line chart to depict the changing weekly Onion
and Brinjal prices for four weeks. Also, give appropriate axes labels, title and keep
marker style as Diamond and marker edge color as ‘red’ for Onion.
import matplotlib.pyplot as plt

# Data for the prices of Onion and Brinjal for four weeks
weeks = ['Week 1', 'Week 2', 'Week 3', 'Week 4']
onion_prices = [40, 42, 45, 48]
brinjal_prices = [30, 35, 37, 40]

# Plotting the line chart


plt.plot(weeks, onion_prices, marker='D', markeredgecolor='red', label='Onion Prices')
plt.plot(weeks, brinjal_prices, marker='o', label='Brinjal Prices')

# Adding title and labels


plt.title('Weekly Onion and Brinjal Prices')
plt.xlabel('Weeks')
plt.ylabel('Prices (in INR)')

# Display legend
plt.legend()
# Show the plot
plt.show()

18. To write a Python program to create a DataFrame for subject-wise average, save it
to a CSV file, and then draw a bar chart using Matplotlib with a width of each bar as
0.25, specifying different colors for each bar. Additionally, provide a proper title and
axes labels for the bar chart.
import pandas as pd
import matplotlib.pyplot as plt

# Data for subject-wise averages


data = {
'Subject': ['Math', 'Science', 'English', 'History', 'Geography'],
'Average_Score': [85, 90, 75, 88, 80]
}

# Create DataFrame
df = pd.DataFrame(data)

# Save DataFrame to CSV file


df.to_csv('subject_average.csv', index=False)

# Plotting the bar chart


plt.bar(df['Subject'], df['Average_Score'], width=0.25, color=['blue', 'green', 'red',
'cyan', 'magenta'])
# Adding title and labels
plt.title('Subject-wise Average Scores')
plt.xlabel('Subjects')
plt.ylabel('Average Score')

# Show the plot


plt.show()

19. To write a Python program to plot a multiple bar chart From CSV file using
Matplotlib for subject wise Scores of Class A, Class B, and Class C. Different colors
represent each class, and subjects include English,Accountancy,Economics,BST and
IP. Proper labels, a title and a legend are displayed on the chart.
import pandas as pd
import matplotlib.pyplot as plt

# Data for subject-wise scores of Class A, Class B, and Class C


data = {
'Subject': ['English', 'Accountancy', 'Economics', 'BST', 'IP'],
'Class A': [85, 90, 78, 88, 92],
'Class B': [80, 85, 79, 82, 88],
'Class C': [75, 80, 70, 78, 85]
}
# Create DataFrame
df = pd.DataFrame(data)

# Set the positions for the bars


bar_width = 0.2
index = range(len(df['Subject']))

# Plotting the multiple bar chart


plt.bar(index, df['Class A'], bar_width, label='Class A', color='blue')
plt.bar([i + bar_width for i in index], df['Class B'], bar_width, label='Class B',
color='green')
plt.bar([i + 2 * bar_width for i in index], df['Class C'], bar_width, label='Class C',
color='red')

# Adding labels and title


plt.xlabel('Subjects')
plt.ylabel('Scores')
plt.title('Subject-wise Scores for Class A, B, and C')
plt.xticks([i + bar_width for i in index], df['Subject']) # Adjust the x-ticks to be
centered
plt.legend()

# Show the plot


plt.show()
20. To write a Python program to plot a Histogram for the following class interval or
range. Also, give appropriate axes name, title and edege color as ‘red’.
import matplotlib.pyplot as plt

# Data for the class intervals


data = [10, 20, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

# Plotting the histogram


plt.hist(data, bins=[0, 20, 40, 60, 80, 100], edgecolor='red')

# Adding title and labels


plt.title('Histogram of Class Intervals')
plt.xlabel('Class Intervals')
plt.ylabel('Frequency')

# Show the plot


plt.show()
SQL Queries

21. With reference to the following relations (tables) EMPLOYEE and JOB complete all
the queries in your practical file.
Create following tables EMPLOYEE and JOB such that Empno and Sno are not null
and unique, name is never blank, Area and Native place is valid, hobby, dept is not
empty.
Table: EMPLOYEE
1. Show empno, name and salary of those who have Sports as hobby.
SELECT Empno, Name, Salary
FROM EMPLOYEE
WHERE Hobby = 'Sports';

2. Show name of the eldest employee.


SELECT Name
FROM EMPLOYEE
WHERE DOB = (SELECT MIN(DOB) FROM EMPLOYEE);
3. Show number of employee area wise.
SELECT Area, COUNT(Empno) AS Num_Employees
FROM EMPLOYEE
GROUP BY Area;

4. Show youngest employees from each Native place.


SELECT Name, Native_place, DOB
FROM EMPLOYEE
WHERE (Native_place, DOB) IN (SELECT Native_place, MAX(DOB)
FROM EMPLOYEE GROUP BY Native_place);

5. Show Sno, name, hobby and salary in descending order of salary.


SELECT Sno, Name, Hobby, Salary
FROM JOB
ORDER BY Salary DESC;

6. Show the hobbies of those whose name pronounces as ‘Abhay’.


SELECT Hobby
FROM EMPLOYEE
WHERE Name = 'ABHAY';

7. Show the appointment date and native place of those whose name starts with ‘A’ or
ends in ‘d’.
SELECT App_date, Native_place
FROM JOB
WHERE Name LIKE 'A%' OR Name LIKE '%d';

8. Show the salary expense with suitable column heading of those who shall retire after
20-jan-2006.
SELECT SUM(Salary) AS Salary_Expense
FROM JOB
WHERE Retd_date > '2006-01-20';
9. Show an additional burden on the company in case the salary of employees having a
hobby as sports, is increased by 10%.
SELECT SUM(Salary * 0.10) AS Additional_Burden
FROM EMPLOYEE
WHERE Hobby = 'Sports';

10. Show the hobby of which there are 2 or more employees.


SELECT Hobby
FROM EMPLOYEE
GROUP BY Hobby
HAVING COUNT(Empno) >= 2;

11. Show how many employee shall retire today if maximum length of service is 20
Years.
SELECT COUNT(Empno)
FROM JOB
WHERE DATEDIFF(CURDATE(), App_date) / 365 >= 20;

12. Show those employee name and date of birth who have served more than 17 years
as on date.
SELECT Name, DOB
FROM EMPLOYEE
WHERE DATEDIFF(CURDATE(), App_date) / 365 > 17;

13. Show names of those who earn more than all of the employees of Sales dept.
SELECT Name
FROM EMPLOYEE
WHERE Salary > ALL (SELECT Salary FROM JOB WHERE Dept =
'Sales');

14. Show names of those who earn more than at least one of the employees of
Marketing dept.
SELECT Name
FROM EMPLOYEE
WHERE Salary > ANY (SELECT Salary FROM JOB WHERE Dept =
'Marketing');

15. Increase salary of the employees by 5 % of their present salary with hobby as Music
or they have completed at least 3 years of service.
UPDATE EMPLOYEE
SET Salary = Salary * 1.05
WHERE Hobby = 'Music' OR DATEDIFF(CURDATE(), App_date) / 365
>= 3;

16. Show the maximum salary and the hobby of the employee.
SELECT MAX(Salary), Hobby
FROM EMPLOYEE
GROUP BY Hobby;

17. Count the number of employees in each department.


SELECT Dept, COUNT(Empno) AS Num_Employees
FROM JOB
GROUP BY Dept;

18. To display the maximum, minimum, sum and average salary of each department.
SELECT Dept, MAX(Salary), MIN(Salary), SUM(Salary),
AVG(Salary)
FROM JOB
GROUP BY Dept;

19. To display ename in lowercase and job in uppercase.


SELECT LOWER(Name), UPPER(Dept)
FROM EMPLOYEE;

20. To display employees name, salary and Area of all the employees working in Agra
SELECT Name, Salary, Area
FROM EMPLOYEE
WHERE Area = 'Agra';

21. Add a new tuple(row) in the table essentially with a hobby as Music.
INSERT INTO EMPLOYEE (Empno, Name, DOB, Native_place, Hobby)
VALUES (130, 'NEW_EMPLOYEE', '1990-01-01', 'Delhi',
'Music');

22. Insert a new column email in job table


ALTER TABLE JOB
ADD email VARCHAR(100);

23. Create a table with values of columns empno, name, and hobby.
CREATE TABLE EMPLOYEE_HOBBY (
Empno INT PRIMARY KEY,
Name VARCHAR(100),
Hobby VARCHAR(50)
);

24. Erase the records of employees from the job table whose hobby is not Sports.
DELETE FROM JOB
WHERE Empno IN (SELECT Empno FROM EMPLOYEE WHERE Hobby !=
'Sports');

25. Remove the table EMPLOYEE.


DROP TABLE EMPLOYEE;

You might also like