Thanks to visit codestin.com
Credit goes to www.scribd.com

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

12th Practical

Uploaded by

devendratomar827
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)
5 views63 pages

12th Practical

Uploaded by

devendratomar827
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/ 63

P.

M SHREE KENDRIYA VIDYALAYA

NARSINGHPUR

SESSION 2025-26
INFORMATICS PRACTICES
: PRACTICAL FILE

SUBMITTED BY: SUBMITTED TO:


DEVENDRA SINGH TOMAR MRS.SHALINEE JADON
CLASS=12TH “B”
ROLL NO.=12207

1|Page
ACKNOWLEDGEMENT

I would lIke to express my specIal thanks of


gratItude to my InformatIcs practIces teacher
mrs. shalInee mam who gave me the golden
opportunIty to do thIs wonderful practIcal fIle
of InformatIcs practIces.

I also lIke to extend my gratItude to provIdIng


me wIth all the requIred facIlItIes.

secondly, I would also lIke to thank my parents


and frIends who helped me a lot In fInalIzIng
thIs practIcal wIthIn the lImIted tIme frame.

2|Page
S.NO PRACTICAL PAGE_
NO.
1. PRACTICAL NO.1
2. PRACTICAL NO.2
3. PRACTICAL NO.3
4. PRACTICAL NO.4
5. PRACTICAL NO.5
6. PRACTICAL NO.6
7. PRACTICAL NO.7
8. PRACTICAL NO.8
9. PRACTICAL NO.9
10. PRACTICAL NO.10
11. PRACTICAL NO.11
12. PRACTICAL NO.12
13. PRACTICAL NO.13
14. PRACTICAL NO.14
15. PRACTICAL NO.15
16. PRACTICAL NO.16
17. PRACTICAL NO.17
18. PRACTICAL NO.18
19. PRACTICAL NO.19
3|Page
20. PRACTICAL NO.20
21. PRACTICAL NO.21
22. PRACTICAL NO.22
23. PRACTICAL NO.23
24. PRACTICAL NO.24
25. PRACTICAL NO.25
26. PRACTICAL NO.26
27. PRACTICAL NO.27
28. PRACTICAL NO.28
29. PRACTICAL NO.29
30. PRACTICAL NO.30
31. PRACTICAL NO.31
32. PRACTICAL NO.32
33. PRACTICAL NO.33
34. PRACTICAL NO.34

REMARK : .

TEACHER SIGN: .

4|Page
Practical no.1

# write a python program to create a series to store 5 students


percentage using dictionary and print all the elements that are
above 75 percentage.

Aim:
To write a Python program to store the percentage of 5 students using
a dictionary and print all the students who have scored more than 75%.

📚 Theory:
In Python, a dictionary is a collection of key-value pairs. It allows
storing related data, such as a student's name (key) and their
percentage (value).
1. Use a dictionary to store 5 student names and their percentage
scores.
2. Iterate through the dictionary to check which students scored
above 75%.
3. Print the names and percentages of those students.
 Dictionaries
 Conditional statements (if)
 Loops (for loop)

5|Page
Code:
students percentages = {"Alice": 82,"Bob": 74,"Charlie": 91, "David": 67,"Eva": 88}

Print ("Students scoring above 75%:")

for name, percentage in students percentages items():


if percentage > 75:
print(f"{name}: {percentage}%")

output:

6|Page
Practical no.2

# .

Aim:
To write a Python program to create a Pandas Series using a NumPy
array.

📚 Theory:
A Series in Pandas is a one-dimensional labeled array capable of
holding any data type (integers, strings, floats, etc.). It is similar to a
NumPy array but with labels (indices).
 NumPy is a library for numerical computations and array
manipulations.
 Pandas builds on NumPy and provides more advanced data
structures, like Series and DataFrames.
 A Pandas Series can be created from a list, dictionary, or NumPy
array.
Creating a Series from a NumPy array involves passing the array to
the pandas.Series() constructor.
.

7|Page
Code:
import numpy as np
import pandas as pd

numpy_array = np.array([10, 20, 30, 40, 50])

series = pd.Series(numpy_array)

print("Pandas Series created from NumPy array:")


print(series)

output:

8|Page
Practical no.3

# write a python program to sort the values of series object s1 in


ascending order of its values and store it into object s2.

Aim:
To write a Python program that sorts the values of a Pandas Series s1
in ascending order and stores the sorted Series into another object s2.

📚 Theory:
A Pandas Series is a one-dimensional labeled array. To sort its
values in ascending order, we use the .sort_values() method.

 Series.sort_values() returns a new Series sorted by the


values.
 By default, it sorts in ascending order.
 The index of the original values is retained unless reset.
This operation is useful when analyzing data in order of magnitude,
rankings, or filtering based on value thresholds.

9|Page
Code:
import pandas as pd

s1 = pd.Series([45, 10, 75, 30, 60])

s2 = s1.sort_values()

print("Original Series (s1):")


print(s1)

print("\nSorted Series (s2) in ascending order:")


print(s2)
output:

10 | P a g e
Practical no.4

# write a python program for performing mathematical operations


on two series object.
Aim:
To write a Python program to perform mathematical operations
(addition, subtraction, multiplication, and division) on two Pandas
Series objects.

📚 Theory:
A Pandas Series is a one-dimensional labeled array that supports
vectorized operations similar to NumPy arrays. You can perform
element-wise mathematical operations directly between two Series
objects.
 These operations are index-aligned, meaning elements with the
same index will be operated on.
 If the indices don’t match, the result will contain NaN for
unmatched index labels.
 Common operations include:
o + (addition)

o - (subtraction)

o * (multiplication)

o / (division)

11 | P a g e
Code:
import pandas as pd

s1 = pd.Series([10, 20, 30, 40, 50])

s2 = pd.Series([1, 2, 3, 4, 5])

addition = s1 + s2

subtraction = s1 - s2

multiplication = s1 * s2

division = s1 / s2

print("Series 1:")

print(s1)

print("\nSeries 2:")

print(s2)

print("\nAddition of s1 and s2:")

print(addition)

print("\nSubtraction of s1 and s2:")

print(subtraction)

print("\nMultiplication of s1 and s2:")

print(multiplication)

print("\nDivision of s1 and s2:")

print(division)

12 | P a g e
output:

13 | P a g e
Practical no.5

write a python program for calculating cube of series values.

Aim:
To write a Python program to calculate the cube of each value in a
Pandas Series.

📚 Theory:

A Pandas Series is a one-dimensional labeled array. You can perform


element-wise operations on a Series just like NumPy arrays.
 To compute the cube of each element in a Series, you raise the
Series to the power of 3 using the ** operator or .pow(3).
 These operations are vectorized, meaning they apply
automatically to each element without writing loops.

14 | P a g e
Code:
import pandas as pd

s = pd.Series([2, 3, 4, 5, 6])

cube = s ** 3
print("Original Series:")
print(s)

print("\nCube of Series values:")


print(cube)

output:

15 | P a g e
Practical no.6

# write a python program to display attributes of a series.

Aim:
To write a Python program to display various attributes of a Pandas
Series such as index, values, dtype, size, and shape.

📚 Theory:

A Pandas Series is a one-dimensional labeled array. It comes with


several useful attributes that provide metadata and structural
information:
 s.index → Displays the index (labels) of the Series.
 s.values → Returns the actual data (as a NumPy array).
 s.dtype → Shows the data type of the elements.
 s.size → Total number of elements.
 s.shape → Returns a tuple indicating the size (1D structure).

16 | P a g e
Code:
import pandas as pd
s = pd.Series([100, 200, 300, 400], index=['a', 'b', 'c', 'd'])

print("Series:")
print(s)
print("\nAttributes of the Series:")
print("Index:", s.index)
print("Values:", s.values)
print("Data Type (dtype):", s.dtype)
print("Size:", s.size)
print("Shape:", s.shape)

output:

17 | P a g e
Practical no.7

#write a python program to display 3 largest values and 3 smallest


values in a series.

Aim:
To write a Python program that displays the three largest and three
smallest values from a Pandas Series.

📚 Theory:
A Pandas Series is a one-dimensional labeled array that supports
efficient data operations. To retrieve the largest or smallest values in
a Series, you can use:
 Series.nlargest(n) → Returns the top n largest values.
 Series.nsmallest(n) → Returns the top n smallest values.

These methods are useful for data analysis tasks like finding top
performers, minimum values, etc.

18 | P a g e
Code:
import pandas as pd
s = pd.Series([50, 20, 90, 10, 70, 30, 100])
largest_values = s.nlargest(3)
smallest_values = s.nsmallest(3)
print("Original Series:")
print(s)
print("\n3 Largest Values:")
print(largest_values)
print("\n3 Smallest Values:")
print(smallest_values)

19 | P a g e
Output:

20 | P a g e
Practical no.8

#write a python program for creating a DataFrame using a nested


list.

Aim:

The aim of this program is to demonstrate how to create a DataFrame


using a nested list in Python with the help of the pandas library. This
is a foundational skill in data handling and analysis.

📚 Theory:

In Python, a nested list is a list that contains other lists as its elements.
Each inner list can represent a row of data. This structure is useful for
representing tabular data, such as a list of students with their names,
ages, and departments.
The pandas library provides a powerful data structure called a
DataFrame, which is essentially a two-dimensional table similar to an
Excel sheet or SQL table. It is widely used in data science, machine
learning, and data analysis due to its flexibility and ease of use.

21 | P a g e
In the given program:
1. A nested list student_data is created, where each sublist
contains one student’s details.
2. A list of column names is defined to label the DataFrame
columns.
3. The pd.DataFrame() function is used to convert the nested
list into a structured DataFrame.
4. The result is printed in a readable tabular format.
Using DataFrames allows for efficient data manipulation, filtering,
sorting, and visualization. Creating a DataFrame from nested lists is an
important starting point for working with real-world datasets.

Code:

import pandas as pd
student_data = [ ["Alice", 20, "Physics"], ["Bob", 21,
"Mathematics"], ["Charlie", 19, "Chemistry"], ["Diana", 22,
"Biology"]]
columns = ["Name", "Age", "Department"]
df = pd.DataFrame(student_data, columns=columns)
print("Student Information:")
print(df )

22 | P a g e
output:

23 | P a g e
Practical no.9

# creating a python program for creating a dataframe using a


dictionary of list.

Aim:
The aim of this program is to demonstrate how to create a pandas DataFrame
using a dictionary of lists. This is a common and efficient way to structure and
manage data in Python for further analysis and manipulation .

Theory:
In Python, a dictionary of lists is a data structure where each key represents a
column name, and each value is a list containing data entries for that column.
When the lists are of equal length, this format maps naturally to a tabular
structure.

The pandas library provides the DataFrame object, which is a two-


dimensional, size-mutable, and heterogeneous data structure with labeled axes
(rows and columns). It's ideal for storing and analyzing structured data.

In this program:

1. A dictionary named student_data is created. Keys like "Name",


"Age", and "Department" represent column headers, and their
corresponding lists hold the column values.
2. The dictionary is passed to the pd.DataFrame() constructor, which
automatically aligns each list into rows and columns.
3. The resulting DataFrame is printed, displaying student data in tabular
form.

24 | P a g e
Code:
import pandas as pd
student_data = {"Name": ["Alice", "Bob", "Charlie", "Diana"],
"Age": [20, 21, 19, 22],
"Department": ["Physics", "Mathematics", "Chemistry",
"Biology"]}
df = pd.DataFrame(student_data)
print("Student Information DataFrame:")
print(df)

output:

25 | P a g e
Practical no.10

# write a python program to display number of rows and columns in


DataFrame.

Aim:
The aim of this program is to display the number of rows and
columns in a DataFrame using Python’s pandas library.
Understanding the structure of a dataset is an essential first step in any
data analysis task.

📚Theory:
A DataFrame is a 2-dimensional labeled data structure provided by
the pandas library, similar to a table or spreadsheet. It is commonly
used for storing and analyzing structured data.
In data analysis, it’s important to know how many rows (records) and
columns (features) a dataset contains. This helps in understanding the
data size and planning operations such as cleaning, visualization, and
machine learning.
In pandas, the .shape attribute of a DataFrame returns a tuple
representing its dimensions:
 df.shape[0] gives the number of rows.
 df.shape[1] gives the number of columns.
26 | P a g e
Code:
import pandas as pd
data = {"Name": ["Alice", "Bob", "Charlie", "Diana"],
"Age": [20, 21, 19, 22],
"Department": ["Physics", "Mathematics", "Chemistry", "Biology"]}
df = pd.DataFrame(data)
print("DataFrame:")
print(df)
rows = df.shape[0]
columns = df.shape[1]
print("\nNumber of Rows:", rows)
print("Number of Columns:", columns)

output:

27 | P a g e
Practical no.11

# write a python program to perform operation on dataframe


(rename,count,update,replace)

Aim:

To write a Python program using the pandas library to perform the


following operations on a DataFrame:
 Rename columns
 Count values in a column
 Update specific cell values
 Replace values in a column

📚Theory:

A DataFrame is a 2-dimensional labeled data structure in the pandas


library, similar to a table in a database or an Excel spreadsheet.
We can perform various data manipulation operations using
DataFrame methods:

28 | P a g e
1. Rename Columns:
Use df.rename(columns={old_name:
o

new_name}) to rename one or more column names.


2. Counting Values:
o Use df['column'].value_counts() to count the

frequency of each unique value in a column.

3. Updating Values:
o Use df.loc[condition, 'column'] =

new_value to update data based on a condition.


4. Replacing Values:
o Use df['column'].replace(old_value,

new_value) to replace specific values in a column.

29 | P a g e
Code:
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Alice'],
'Age': [25, 30, 35, 40, 29, 25],
'Department': ['HR', 'IT', 'IT', 'Finance', 'HR', 'HR']}
df = pd.DataFrame(data)
print(df)
df = df.rename(columns={'Name': 'Employee Name', 'Age':
'Employee Age'})
print("\n Renaming Columns:")
print(df)
department_counts = df['Department'].value_counts()
print("\n Count:")
print(department_counts)
df.loc[df['Employee Name'] == 'Eve', 'Employee Age'] = 28
print("\n Updating Eve's Age:")
print(df)
df['Department'] = df['Department'].replace('HR', 'Human
Resources')
print("\n Replacing 'HR' with 'Human Resources':")
print(df)

30 | P a g e
output:

31 | P a g e
32 | P a g e
Practical no.12

# write a python program to filter the data from a dataframe.

Aim:
To write a Python program that filters specific rows from a Pandas
DataFrame based on given conditions.

📚Theory:
In data analysis, filtering means selecting rows from a dataset that
meet certain conditions.
In Pandas, filtering is done using:
 Boolean indexing — applying a condition to a DataFrame that
returns True or False for each row.
 loc[] or iloc[] methods — selecting rows by labels or
positions.

33 | P a g e
Code:
import pandas as pd

data = { 'Name': ['Amit', 'Priya', 'Rahul', 'Neha', 'Ravi'],


'Age': [23, 29, 21, 25, 30],
'Score': [85, 92, 76, 89, 95]}

df = pd.DataFrame(data)
print(df)
filtered_df = df[df['Age'] > 25]
print("\nFiltered DataFrame (Age > 25):")
print(filtered_df)

output:

34 | P a g e
Practical no.13

#write a python program to display the attribute of the DataFrame.

Aim:
To write a Python program to display the attributes of a Pandas
DataFrame.

📚Theory:
In Pandas, a DataFrame is a 2-dimensional labeled data structure
similar to a table with rows and columns.
Attributes are in-built properties of a DataFrame that provide useful
information about the dataset without modifying it.
Common DataFrame attributes:
 df.shape → Returns number of rows and columns as a tuple.
 df.size → Returns total number of elements.
 df.ndim → Returns the number of dimensions.
 df.index → Returns index (row labels) of the DataFrame.
 df.columns → Returns column labels.
 df.values → Returns data as a NumPy array.
 df.dtypes → Returns data types of each column.

35 | P a g e
Code:

import pandas as pd

data = {'Name': ['Amit', 'Priya', 'Rahul'],


'Age': [23, 29, 21],
'Score': [85, 92, 76]}

df = pd.DataFrame(data)
print("DataFrame:")
print (df)
print ("Shape:", df.shape)
print ("Size:", df.size)
print ("Dimensions:", df.ndim)
print ("Index:", df.index)
print ("Columns:", df.columns)
print ("Values:\n", df.values)
print ("Data Types:\n", df.dtypes)

36 | P a g e
Output:

37 | P a g e
Practical no.14

# Given dataframe df write a python program to display only the


name, age and position for all rows.

Aim:
name gender position city age projects Budget
0 Rabina F Manager Bangalore 30 13 48
1 Evan M Programmer NewDelhi 27 17 13
2 Jia F Manager Chennai 32 16 32
3 Lalit M Manager Mumbai 40 20 21

To write a Python program to display only the Name, Age, and


Position columns for all rows from a given DataFrame.

📚Theory:
A DataFrame in Pandas is a 2D tabular data structure with labeled
rows and columns.
To select multiple specific columns, we can use:
df [['col1', 'col2', 'col3']]

38 | P a g e
code:

import pandas as pd

data = {'Name': ['Rubina', 'Evan', 'Jia', 'Lalit'],


'Gender': ['F', 'M', 'F', 'M'],
'Position': ['Manager', 'Programmer', 'Manager', 'Manager'],
'City': ['Bangalore', 'New Delhi', 'Chennai', 'Mumbai'],
'Age': [30, 27, 32, 40],
'Project': [13, 17, 16, 20],
'Budget': [48, 13, 32, 21]}
df = pd.DataFrame(data)
print ("Original DataFrame:")
print(df)
print (df [['Name', 'Age', 'Position']])

39 | P a g e
Output:

40 | P a g e
Practical no.15

# write a python program to perform writing and reading


operational in a CSV file.

Aim:
To write a Python program to perform writing and reading operations
in a CSV (Comma-Separated Values) file using the Pandas library.

📚Theory:
A CSV file is a plain text file used to store tabular data where each
line represents a row and values are separated by commas.
In Python, the Pandas library makes it easy to handle CSV files
using:
 to_csv() → Writes data from a DataFrame to a CSV file.
Syntax:
df.to_csv("filename.csv", index=False)
 read_csv() → Reads data from a CSV file into a DataFrame.
Syntax:
pd.read_csv("filename.csv")

41 | P a g e
code:
import pandas as pd
data = {'Name': ['Amit', 'Priya', 'Rahul'],
'Age': [23, 29, 21],
'Score': [85, 92, 76]}
df = pd.DataFrame(data)

df.to_csv("students.csv", index=False)
print("Data written to ‘students.csv’:"
new_df = pd.read_csv("students.csv")
print("\nData read from 'students.csv':")
print(new_df)

42 | P a g e
output:
The data of students.csv is showing on notepad

43 | P a g e
Practical no.16

# write a python program for plotting a line chart.

Aim:
To write a Python program to plot a line chart using the Matplotlib
library.

📚Theory:
A line chart is a type of graph used to display data points connected
by straight lines.
It is useful for showing trends over time or continuous data.
In Python, the Matplotlib library is commonly used for plotting
charts.
The function plt.plot(x, y) is used to create a line chart, where:
 x → Values on the horizontal axis (independent variable)
 y → Values on the vertical axis (dependent variable)
Other useful functions:
 plt.title() → Sets chart title
 plt.xlabel() / plt.ylabel() → Label axes
 plt.grid() → Shows grid lines
 plt.show() → Displays the chart
44 | P a g e
code:

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",


"Aug"]
sales = [12000, 15000, 18000, 17000, 21000, 25000, 23000, 27000]
plt.plot(months, sales, label= ‘Data’, color='green', linestyle='-',
linewidth=2)
plt.title("Monthly Sales Report (2025)")
plt.xlabel("Months")
plt.ylabel("Sales in ₹")
plt.legend()
plt.grid(True)
plt.show()

45 | P a g e
Output:

46 | P a g e
Practical no.17

#write a python program for plotting a bar chart from a csv file .

Aim:
To write a Python program to plot a bar chart from data stored in a
CSV file using the Pandas and Matplotlib libraries.

📚Theory:
A bar chart represents data using rectangular bars where the length of
each bar is proportional to its value.
It is useful for comparing categories.
Steps to plot a bar chart from a CSV file in Python:
1. Read CSV file using pd.read_csv().
2. Extract columns for categories (X-axis) and values (Y-axis).
3. Plot bar chart using plt.bar().
4. Add title, axis labels, and grid for better readability.

47 | P a g e
Code:

import pandas as pd
import matplotlib.pyplot as plt

data = {'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],


'Sales': [12000, 15000, 17000, 13000, 18000]}
df = pd.DataFrame(data)
df.to_csv("sales_data.csv", index=False)
sales_df = pd.read_csv("sales_data.csv")
plt.bar(sales_df['Month'], sales_df['Sales'], color='skyblue')

plt.title("Monthly Sales Report")


plt.xlabel("Month")
plt.ylabel("Sales in ₹")

plt.show()

48 | P a g e
output:

49 | P a g e
Practical no.18

# write a python program for plotting a horizontal bar chart from a


csv file.

Aim:
To write a Python program that reads data from a CSV file and plots a
Horizontal Bar Chart using Matplotlib.

📚Theory:
 Horizontal Bar Chart is similar to a vertical bar chart, but the bars are
drawn horizontally.
 It is useful when category names are long or when you want to emphasize
values across categories.
 CSV (Comma-Separated Values) file is a plain text file that stores data
in tabular format.
 We can use the pandas library to read CSV files and matplotlib.pyplot
to plot graphs.
 Function used:
o plt.barh(y, width) → Plots horizontal bars.

o pd.read_csv("filename.csv") → Reads CSV file


into a DataFrame.

50 | P a g e
Code:
import pandas as pd
import matplotlib.pyplot as plt

data = {'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],


'Sales': [12000, 15000, 17000, 13000, 18000]}
df = pd.DataFrame(data)
df.to_csv("sales_data.csv", index=False)
sales_df = pd.read_csv("sales_data.csv")
plt.barh(sales_df['Month'], sales_df['Sales'], color='skyblue')

plt.title("Monthly Sales Report")


plt.xlabel("Month")
plt.ylabel("Sales in ₹")

plt.show()

51 | P a g e
output:

52 | P a g e
Practical no.19

#write a python program for plotting histogram.

Aim:
To write a Python program to plot a Histogram using Matplotlib in
Python.

📚Theory:
 A Histogram is a graphical representation that organizes a group
of data points into user-specified ranges (bins).
 It is used to show the frequency distribution of continuous data.
 In Python, Matplotlib provides the plt.hist() function to plot
histograms.
 Important Parameters of plt.hist():
o data → The list or array of numeric values.

o bins → Number of intervals to group the data.

o color → Color of the bars.

o edgecolor → Color of the bar borders.

53 | P a g e
code:

import matplotlib.pyplot as plt

marks = [45, 56, 67, 89, 90, 45, 67, 72, 88, 90,
56, 45, 67, 70, 80, 90, 85, 66, 75, 82]

plt.hist(marks, bins=[40, 50, 60, 70, 80, 90, 100],


color='blue', edgecolor='black', label='Marks Data')

plt.xlabel('Marks Range')
plt.ylabel('Number of Students')
plt.title('Histogram - Marks Distribution')
plt.legend()

plt.show()

54 | P a g e
output:

55 | P a g e
Practical no.20

56 | P a g e
57 | P a g e
58 | P a g e
59 | P a g e
60 | P a g e
61 | P a g e
62 | P a g e
63 | P a g e

You might also like