0% found this document useful (0 votes)
37 views

Info Practical[1]

Uploaded by

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

Info Practical[1]

Uploaded by

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

SMART INDIAN SCHOOL

Bharatiya Vidya Bhavan,Kuwait

PRACTICAL FILE

INFORMATICS PRACTICES(065)

STUDENT NAME : Saad Shaukat Shaikh

GRADE AND DIVISION :12-Taurus

REGISTRATION NUMBER:

ACADEMIC YEAR :2024-2025

SUBMITTED TO : Ms.Karthiga
BONAFIDE CERTIFICATE

This is to certify that this practical file is the bonafide work of Mr. Saad Shaukat
Shaikh of Grade XII, Section Taurus, who has satisfactorily completed the
Practical Assignments in Informatics Practices for the AISSCE as prescribed by
the CBSE during the academic year 2024-25.

Submitted for Viva-Voce examination held at SMART INDIAN SCHOOL,


KUWAIT, on ……………………

Internal Examiner Principal


Signature: Mr.Mahesh Iyer
Signature:

External Examiner School Seal


Signature:
INDEX

S.No PROGRAM TITLE PAGE


NO

1. Topic:Pandas Series 1-14

2. Topic:Pandas Dataframes 15-48

3. Topic:Data Visualization 49-84

4. Topic:CSV Programs 85-96

5 Topic:SQL Queries 97-133


Output
Topic:Pandas Series

1.Write a program in Python to create pandas Series object from


dictionary.

Aim:
to create pandas Series object from dictionary

Software Required:
Spyder IDE

Program
import pandas as pd
data = {'a': 1, 'b': 2, 'c': 3}
series = pd.Series(data)
print(series)

Result
The following program to create pandas Series object from dictionary has
been successfully executed and obtained the output.
Output
2. Write a program in Python to create pandas Series object from
ndarray.

Aim:
to create pandas Series object from ndarray

Software Required:
Spyder IDE

Program
import pandas as pd
import numpy as np
ar = np.array([10, 20, 30])
series = pd.Series(ar)
print(series)

Result
The following program to create pandas Series object from ndarray has been
successfully executed and obtained the output.
Output
3.Write a program to perform mathematical operation on two
Pandas Series.
s1=[22,44,66,88,100] ,s2=[11,22,33,44,55].

Aim:
to perform mathematical operation on two Pandas Series

Software Required:
Spyder IDE

Program
s1 = pd.Series([22, 44, 66, 88, 100])
s2 = pd.Series([11, 22, 33, 44, 55])
print("Addition:", s1 + s2)
print("Subtraction:", s1 - s2)
print("Multiplication:", s1 * s2)
print("Division:", s1 / s2)

Result
The following program to perform mathematical operation on two Pandas
Series has been successfully executed and obtained the output.
Output
4.Write a pandas program to create a Series object Temp1 that
stores temperature of seven days in it.Now define indexes as
‘Sunday’,’Monday’….upto ‘Saturday’and print the Series again.Now
print attributes of the Series as well as average temperature of 7
days.
Aim:
to create a Series object Temp1 that stores temperature of seven days in
it,print it and find the average temperature
Software Required:
Spyder IDE

Program
temp = pd.Series([30, 32, 33, 29, 31, 28, 30], index=['Sunday', 'Monday',
'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
print("Series:\n", temp)
print("Attributes:")
print("Index:", temp.index)
print("Values:", temp.values)
print("Average temperature:", temp.mean())

Result
The following program to create a Series object Temp1 that stores
temperature of seven days in it,print it and find the average temperature has
been successfully executed and obtained the output.
Output
5. Write a Pandas program to add some data on an existing Series.

Aim:
to add some data on an existing Series

Software Required:
Spyder IDE

Program
import pandas as pd
s1 = pd.Series([1, 2, 3])
print(s1)
s2 = pd.Series([4, 5, 6])
print(s2)
s=pd.concat([s1, s2])
print(s)

Result
The following program to add some data on an existing Series has been
successfully executed and obtained the output.
Output
6.Create a Series from an array of 25 numbers.Print as per the
following queries:
S1=[21,36,37,28,38,27,33,49,12,58,58,37,34,41,39,26,50,21,19,34,3
4,41,4 8,18]
a. Print second element.
b. Print 5th element onwards.
c. Print all the elements in reverse order.
d. Print 10th to 20th elements.
e. Print 5th to last elements jumping 2 elements.
f. Print 20th to last elements by adding 5 in each element.
g. Print twice of each element.
h. Print bottom 5 elements 3,7 10,15,19,24
Aim:
to create a Series from an array of 25 numbers. Print as per the following
queries

Software Required:
Spyder IDE

Program
Lst=[21,36,37,28,38,27,33,49,12,58,58,37,34,41,39,26,50,21,19,34,34,41,4,
8,18,36]
s1=pd.Series(Lst)
line='_'*50
print("Original Series",line)
print(s1)
print(line)
print("Second Element is:",s1[1])
Output
print(line)
print("5th element onwards is\n"+line)
print(s1[4:])
print("Elements in reverse order:\n"+line)
print(s1[::-1])
print("10th to 20th elements is:\n"+line)
print(s1[9:12])
print(" 5th to last element skip by 2 elements:\n"+line)
print(s1[4:2])
print("20th to last element by adding 5 to each element is :\n",line)
print(s1[20:]+5)
print(line)
print("Twice of each element is \n"+line)
print(s1*2)
print(line)
print("Bottom 5 elements is:\n"+line)
print(s1.tail())
print(s1[3],s1[7],s1[10],s1[15],s1[19],s1[23])

Result
The following program to create a Series from an array of 25 numbers. Print
as per the following queries has been successfully executed and obtained the
output.
Output
Topic:Pandas Dataframes
1.Write a Python program to create a dataframe as given below and
display all its attributes(index, columns, shape, size, axes, rows and
columns).
Aim:
to create a dataframe as given below and display all its attributes(index,
columns, shape, size, axes, rows and columns)
Software Required:
Spyder IDE
Program
import pandas as pd
data = {'Name': ['Abdullah', 'Febin', 'Omar', 'Zahid'],
'Age': [25, 30, 35, 40],
'City': ['Jabriya', 'Abbasiya', 'Fahaheel', 'Hawally']}
df = pd.DataFrame(data)
print("DataFrame:")
print(df)
print("\nAttributes:")
print("Index:", df.index)
print("Columns:", df.columns)
print("Shape (rows, columns):", df.shape)
print("Size (total elements):", df.size)
print("Axes:", df.axes)
print("Number of Rows:", df.shape[0])
print("Number of Columns:", df.shape[1])

Result
The following program to create a Series object Temp1 that stores
temperature of seven days in it,print it and find the average temperature has
been successfully executed and obtained the output.
Output
2.Write a Python program to create a dataframe Cricket with
columns playername, Age, TotalScore, Century, and Fifties for ten
players.(Add player_id from 101 to 110 in the dataframe during
creation.
a.Now using head() and tail() function, display top 5 rows, bottom 5
rows, last 6 rows.
b. Display details of player_id 101 using loc
c.Display rows of player_id 103,104,107 using loc.
d.Displays rows of player_id 103,104,107 using iloc.
e.Using slicing display roll number 1,3,5,7
f.Print the Transpose of the dataframe.
Aim:
to create a dataframe Cricket with columns playername, Age, TotalScore,
Century, and Fifties for ten players.(Add player_id from 101 to 110 in the
dataframe during creation
Software Required:
Spyder IDE
Program
import pandas as pd
data = {
'player_id': [101, 102, 103, 104, 105, 106, 107, 108, 109, 110],
'playername': ['Dhoni', 'Sachin', 'Virat', 'Shikar', 'Rohit',
'Suresh', 'Chris', 'David', 'Gautham', 'Yuvraj'],
'Age': [36, 47, 32, 34, 33, 33, 41, 34, 39, 38],
'TotalScore': [10599, 18426, 11867, 5688, 9115, 5165, 10480, 5303, 5238,
8609],
'Century': [9, 49,43,17,29,5,25,18,11,14],
'Fifties': [73,96,58,29,43,36,54,21,34,52]
}
cricket_df = pd.DataFrame(data)
print("Cricket DataFrame:")
Output
print(cricket_df)
print("\nTop 5 rows using head():")
print(cricket_df.head())
print("\nBottom 5 rows using tail():")
print(cricket_df.tail())
print("\nLast 6 rows using tail():")
print(cricket_df.tail(6))
print("\nDetails of player_id 101:")
print(cricket_df.loc[cricket_df['player_id'] == 101])
print("\nDetails of player_id 103, 104, 107 using loc:")
print(cricket_df.loc[cricket_df['player_id'].isin([103, 104, 107])])
indices = cricket_df[cricket_df['player_id'].isin([103, 104, 107])].index
print("\nDetails of player_id 103, 104, 107 using iloc:")
print(cricket_df.iloc[indices])
print("\nDetails of player_id 101, 103, 105, 107 using slicing:")
print(cricket_df.iloc[[0, 2, 4, 6]])
print("\nTranspose of the DataFrame:")
print(cricket_df.T)

Result
The following program to create a dataframe Cricket with columns
playername, Age, TotalScore, Century, and Fifties for ten players.(Add
player_id from 101 to 110 in the dataframe during creation has been
successfully executed and obtained the output.
Output
3.Write a program to create the following DataFrame namely Aid
that stores the aid by NGOs for different states
state toys books uniform shoes
Andhra 4656 34445 100 400
Odisha 5767 45554 500 600
Bihar 7684 45848 500 688
Jharkhand 1234 56574 488 700
W.B 5766 56575 399 456

Now display the following:


a. Show the data of Toys Column
b. Show the data of Books and uniform columns.
c. Show the data of Toys and Uniform columns from top 3 rows(use
loc).
d. Show the data of first 3 rows and first 3 columns(using iloc)
e. Set the state as index and display the DataFrame
f. Show the data for Toys, Uniform and Shoes columns of
Andhra,Bihar and W.B.
g. Reset the index and show the DataFrame.
Aim:
to create the following DataFrame namely aid that stores the aid by NGOs for
different states and perform aforementioned activities
Software Required:
Spyder IDE
Program
import pandas as pd
data = { 'State': ['Andhra', 'Odisha', 'Bihar', 'Jharkhand', 'W.B'],
'Toys': [4656, 5767, 7684, 1234, 5766],
'Books': [34445, 45554, 45848, 56574, 56575],
'Uniform': [100, 500, 500, 488, 399],
'Shoes': [400, 600, 688, 700, 456]
}
Output
aid_df = pd.DataFrame(data)
print("Aid DataFrame:")
print(aid_df)
print("\nData of Toys Column:")
print(aid_df['Toys'])
print("\nData of Books and Uniform Columns:")
print(aid_df[['Books', 'Uniform']]))
print("\nData of Toys and Uniform Columns from Top 3 Rows:")
print(aid_df.loc[:2, ['Toys', 'Uniform']])
print("\nData of First 3 Rows and First 3 Columns:")
print(aid_df.iloc[:3, :3])
aid_df_indexed = aid_df.set_index('State')
print("\nDataFrame with State as Index:")
print(aid_df_indexed)
print("\nData for Toys, Uniform, and Shoes Columns of Andhra, Bihar, and
W.B:")
print(aid_df_indexed.loc[['Andhra', 'Bihar', 'W.B'], ['Toys', 'Uniform', 'Shoes']])
aid_df_reset = aid_df_indexed.reset_index()
print("\nDataFrame After Resetting the Index:")
print(aid_df_reset)

Result
The following program to create the following DataFrame namely aid that
stores the aid by NGOs for different states and perform aforementioned
activities has been successfully executed and obtained the output.
Output
4.Write a program to create the following
DataFrame showing quarterly sale year-wise,now
write Python code as per the given questions.
Yr1 Yr2 Yr3
Qtr1 3500 5500 9000
Qtr2 5600 4600 7800
Qtr3 3300 6700 7800
Qtr4 4500 8900 2200

1) Display the DataFrame


2) Write a menu driven program to
extract data from DataFrame
a)Row-wise
b) Row-wise Series Object(using iterrows())
c) Perform iteration column-wise also.(use
iteritems() functions, make menu driven).

Aim:

to create the following DataFrame showing


quarterly sale year-wise and writing a Python
code as per the given questions.
Software Required:
Spyder IDE
Program
import pandas as pd
data = {'Yr1': [3500, 5600, 3300, 4500],
'Yr2': [5500, 4600, 6700, 8900],
'Yr3': [9000, 7800, 7800, 2200]}
index_labels = ['Qtr1', 'Qtr2', 'Qtr3', 'Qtr4']
sales_df= pd.DataFrame(data, index=index_labels)
print("Quarterly Sales DataFrame:")
print(sales_df)
while True:
Output
print("\nMenu:")
print("1. Display DataFrame row-wise")
print("2. Display row-wise Series objects (using iterrows())")
print("3. Perform iteration column-wise (using iteritems())")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
print("\nRow-wise Data:")
for index, row in sales_df.iterrows():
print(f"{index}: {row.to_dict()}")
elif choice == '2':
print("\nRow-wise Series Objects:")
for index, row in sales_df.iterrows():
print(f"Index: {index}, Series Object:\n{row}")
elif choice == '3':
print("\nColumn-wise Data:")
for A,B in sales_df.iteritems():
print(f"Column: {A}, Data:\n{B}")
elif choice == '4':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice! Please try again.")

Result
The following program to create the following DataFrame showing
quarterly sale year-wise and writing a Python code as per the given
questions has been successfully executed and obtained the output.
Output
5. Write a python program to create two
DataFrames and perform 4 basic arithmetic
operations such as add, substract, multiply and
divide.

Aim:
to create two DataFrames and perform 4 basic arithmetic operations such as
add, substract, multiply and divide
Software Required:
Spyder IDE
Program
import pandas as pd
data1 = {
'A': [10, 20, 30],
'B': [40, 50, 60],
'C': [70, 80, 90]
}
df1 = pd.DataFrame(data1, index=['Row1', 'Row2', 'Row3'])
data2 = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
}
df2 = pd.DataFrame(data2, index=['Row1', 'Row2', 'Row3'])
print("DataFrame 1:")
print(df1)
Output
print("\nDataFrame 2:")
print(df2)
add_result = df1 + df2
print("\nAddition of DataFrames:")
print(add_result)
subtract_result = df1 - df2
print("\nSubtraction of DataFrames:")
print(subtract_result)
multiply_result = df1 * df2
print("\nMultiplication of DataFrames:")
print(multiply_result)
divide_result = df1 / df2
print("\nDivision of DataFrames:")
print(divide_result)

Result
The following program to create two DataFrames and perform 4 basic
arithmetic operations such as add, substract, multiply and divide has been
successfully executed and obtained the output.
Output
i)

ii)

iii)
6.Write a program to create the following
DataFrame as per given row and columns in it.
SName English Math Physics Chemistry Info
1 Scott 78 79 87 97 94
2 Michel 75 90 57 92 97
3 Thomas 67 85 76 80 90
4 Mathews 80 90 88 80 99
5 David 87 95 78 95 100
Now peform the following by writing Python code.
i) Add a column Total showing sum of marks of all
subjects.
ii) To increase 5 marks in the ‘Total” column for all
students.
iii) Add one more column Percentage, Calculate on the
basis of ‘Total” marks
obtained out of 500.
iv) Add a new row in the above DataFrame using loc.

v) Add two more rows together in the above


DataFrame using append.
vi) Now modify the English marks of Thomas as
70,accordingly update his total and
Percentage.

vii) Display the DataFrame.


Aim:
to create the following DataFrame as per given row and columns
in it
Software Required:
Spyder IDE
Program
import pandas as pd
data = {'SName': ['Scott', 'Michel', 'Thomas', 'Mathews', 'David'],
'English': [78, 75, 67, 80, 87], 'Math': [79, 90, 85, 90, 95],
'Physics': [87, 57, 76, 88, 78], 'Chemistry': [97, 92, 80, 80, 95],
'Info': [94, 97, 90, 99, 100]}
df = pd.DataFrame(data)
df['Total'] = df[['English', 'Math', 'Physics', 'Chemistry', 'Info']].sum(axis=1)
Output
iv)

v),vi),vii)
df['Total'] += 5
df['Percentage'] = (df['Total'] / 500) * 100
df.loc[5] = ['Jack', 85, 88, 82, 89, 90, 0, 0] # Adding default Total and
Percentage
df.loc[5, 'Total'] = df.loc[5, ['English', 'Math', 'Physics', 'Chemistry',
'Info']].sum()
df.loc[5, 'Percentage'] = (df.loc[5, 'Total'] / 500) * 100
new_rows = pd.DataFrame({
'SName': ['Rachel', 'Monica'],
'English': [90, 92],
'Math': [85, 88],
'Physics': [78, 80],
'Chemistry': [85, 90],
'Info': [88, 92],
'Total': [0, 0], # Initialize Total
'Percentage': [0, 0] })
new_rows['Total'] = new_rows[['English', 'Math', 'Physics', 'Chemistry',
'Info']].sum(axis=1)
new_rows['Percentage'] = (new_rows['Total'] / 500) * 100
df = pd.concat([df, new_rows], ignore_index=True)
df.loc[df['SName'] == 'Thomas', 'English'] = 70
df.loc[df['SName'] == 'Thomas', 'Total'] = df.loc[df['SName'] == 'Thomas',
['English', 'Math', 'Physics', 'Chemistry', 'Info']].sum(axis=1)
df.loc[df['SName'] == 'Thomas', 'Percentage'] = (df.loc[df['SName'] ==
'Thomas', 'Total'] / 500) * 100
print("\nUpdated DataFrame:")
print(df)
Result
The following program to create the following DataFrame as per
given row and columns in has been successfully executed and obtained
the output.
Output
7.Consider the DataFrame as created below:

Empco Ename Job Salary Bonus Zone


de
10 E101 Sam Clerk 20000 1000 West
20 E102 Kain Manag 50000 2500 East
er
30 E103 Scott Clerk 18000 100 East
40 E104 Joy Analyst 55000 7000 North
50 E105 Tom Manag 65000 5000 West
er

Write command and output to perform the following


queries in Pandas.
a. To display those employees whose bonus is greater
than equal to 5000.
b. To display all those records whose salary lies in the
range of 50000 to 70000
c. To display empcode, ename and salary of ‘Manager”
d. To display those records whose Zone is either ‘East” or
“West only.
e. To display Ename,Job, Salary of those employees
whose job is “Manage”
and Salary is 65000
Aim:
to create the following DataFrame to perform the following queries
in Pandas
Software Required:
Spyder IDE
Program
import pandas as pd
data = {
Output
'Empcode': ['E101', 'E102', 'E103', 'E104', 'E105'],
'Ename': ['Sam', 'Kain', 'Scott', 'Joy', 'Tom'],
'Job': ['Clerk', 'Manager', 'Clerk', 'Analyst', 'Manager'],
'Salary': [20000, 50000, 18000, 55000, 65000],
'Bonus': [1000, 2500, 100, 7000, 5000],
'Zone': ['West', 'East', 'East', 'North', 'West']
}
df = pd.DataFrame(data)
print("\nEmployees whose bonus is greater than or equal to 5000:")
result_a = df[df['Bonus'] >= 5000]
print(result_a)
print("\nEmployees whose salary lies between 50000 and 70000:")
result_b = df[(df['Salary'] >= 50000) & (df['Salary'] <= 70000)]
print(result_b)
print("\nEmpcode, Ename, and Salary of Managers:")
result_c = df[df['Job'] == 'Manager'][['Empcode', 'Ename', 'Salary']]
print(result_c)
print("\nEmployees whose Zone is either 'East' or 'West':")
result_d = df[df['Zone'].isin(['East', 'West'])]
print(result_d)
print("\nEname, Job, and Salary of Managers with a Salary of 65000:")
result_e = df[(df['Job'] == 'Manager') & (df['Salary'] == 65000)][['Ename',
'Job', 'Salary']]
print(result_e)
Result
The following program to create the following DataFrame to perform
the following queries in Pandas has been successfully executed and
obtained the output.
Output
Topic:Data Visualization

1.Write a python program to generate line


graph with suitable title and labels.Where x is
the year of performance with values
2014,2015,2016,207,2018 and 2019 and Y axis
shows the profit of a particular company in Rs.
(Millions)

Aim:
to generate line graph with suitable title and labels
Software Required:
Spyder IDE

Program
import matplotlib.pyplot as plt
years = [2014, 2015, 2016, 2017, 2018, 2019] # X-axis values
profits = [50, 75, 100, 125, 150, 175] # Y-axis values in Rs. (Millions)
plt.figure(figsize=(8, 5))
plt.plot(years, profits, marker='o', linestyle='-', color='k', label='Profit (in Rs.
Millions)')
plt.title('Yearly Performance of the Company', fontsize=14)
plt.xlabel('Year', fontsize=12)
plt.ylabel('Profit (in Rs. Millions)', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend(loc='upper left')
plt.show()

Result
The following program to generate line graph with suitable title and
label has been successfully executed and obtained the output.
Output
2.Given the following data of rainfall in different
zones in India in mm for 12 months.Create
multiple line charts in a figure to observe any
trends form Jan to Dec.
Zones Jan Feb Mar Apr May Jun Ju Aug Sep Oct Nov De
l c
Zone 14 13 13 19 16 20 15 17 19 17 15 12
A
Zone 11 16 13 11 12 17 13 20 15 16 17 13
B
Aim:
to Create multiple line charts in a figure to observe any trends
form Jan to Dec
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

zone_a_rainfall = [14, 13, 13, 19, 16, 20, 15, 17, 19, 17, 15, 12]

zone_b_rainfall = [11, 16, 13, 11, 12, 17, 13, 20, 15, 16, 17, 13]

plt.figure(figsize=(10, 6))

plt.plot(months, zone_a_rainfall, marker='o', linestyle='-', color='k', label='Zone A')

plt.plot(months, zone_b_rainfall, marker='s', linestyle='--', color='r', label='Zone B')

plt.title('Rainfall Trends in Different Zones (Jan to Dec)', fontsize=16)

plt.xlabel('Months', fontsize=12)

plt.ylabel('Rainfall (mm)', fontsize=12)

plt.grid(True, linestyle='--', alpha=0.7)

plt.legend(loc='upper right', fontsize=10)

plt.tight_layout()

plt.show()

Result
The following program to Create multiple line charts in a figure to
observe any trends form Jan to Dec has been successfully executed
and obtained the output.
Output
3.Given the school result data,analyse the performance of
the students on different parameters eg:subject wise or
class wise.

Aim:
to create line charts on students performance subject-wise and
class-wise.
Software Required:
Spyder IDE
Program
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Student': ['John', 'Emma', 'Liam', 'Olivia', 'Noah', 'Ava'],
'Class': [10, 10, 9, 9, 10, 9],
'Math': [85, 90, 75, 95, 65, 78],
'Science': [78, 82, 88, 91, 72, 85],
'English': [88, 79, 84, 89, 74, 83],
'Social Studies': [92, 85, 80, 87, 68, 80]
}
df = pd.DataFrame(data)
print("School Result Data:")
print(df)
subject_avg = df[['Math', 'Science', 'English', 'Social Studies']].mean()
print("\nSubject-wise Average Scores:")
print(subject_avg)
Output
class_avg = df.groupby('Class')[['Math', 'Science', 'English', 'Social
Studies']].mean()
print("\nClass-wise Average Scores:")
print(class_avg)
plt.figure(figsize=(8, 5))
subject_avg.plot(kind='bar', color=['red', 'blue', 'orange', 'green'],
alpha=0.7)
plt.title('Subject-wise Average Performance', fontsize=16)
plt.xlabel('Subjects', fontsize=12)
plt.ylabel('Average Scores', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
class_avg.plot(kind='bar', color=['red', 'blue', 'orange', 'green'], figsize=(10,
6), alpha=0.8)
plt.title('Class-wise Average Performance', fontsize=16)
plt.xlabel('Class', fontsize=12)
plt.ylabel('Average Scores', fontsize=12)
plt.legend(title="Subjects")
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

Result
The following program to create line charts on students performance
subject-wise and class-wise has been successfully executed and obtained
the output.
Output
4.Write a program to analyze and plot appropriate
multiple bar char with title and legend.
Aim:
to analyze and plot appropriate multiple bar chart with title and
legend
Software Required:
Spyder IDE
Program
import pandas as pd
import matplotlib.pyplot as plt
data = {'Subjects': ['Math', 'Science', 'English', 'Social Studies'], 'Class 9':
[82, 88, 85, 83],'Class 10': [80, 77, 80, 82]}
df = pd.DataFrame(data)
x = range(len(df['Subjects']))
bar_width = 0.35
plt.figure(figsize=(10, 6))
plt.bar(x, df['Class 9'], width=bar_width, label='Class 9', color='pink',
edgecolor='black')
plt.bar([p + bar_width for p in x], df['Class 10'], width=bar_width,
label='Class 10', color='grey', edgecolor='black')
plt.title('Comparison of Class Performance by Subjects', fontsize=16)
plt.xlabel('Subjects', fontsize=12)
plt.ylabel('Scores', fontsize=12)
plt.xticks([p + bar_width / 2 for p in x], df['Subjects'
plt.legend(title='Class')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
Result
The following program to analyze and plot appropriate multiple bar char
with title and legend has been successfully executed and obtained the
output.
Output
5.Consider the data given below in the
table.Create a bar chart depicting the
downloads of the app.
AppName Total Downloads
Angry Bird 197000
Teen Titan 209000
Marvel Comics 414000
Color Me 196000
Fun Run 272000
Crazy Taxi 311000
Igram Pro 213000
Wapp Pro 455000
Math Formulas 278000
Aim: To analyze and plot a bar chart
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt
apps = [ "Angry Bird", "Teen Titan", "Marvel Comics", "Color Me", "Fun Run",
"Crazy Taxi", "Igram Pro", "Wapp Pro", "Math Formulas"]
downloads = [197000, 209000, 414000, 196000, 272000, 311000, 213000,
455000, 278000]
plt.figure(figsize=(12, 6))
plt.bar(apps, downloads, color='yellow', edgecolor='black')
plt.title('App Downloads Comparison', fontsize=16)
plt.xlabel('App Name', fontsize=12)
plt.ylabel('Total Downloads', fontsize=12)
plt.xticks(rotation=45, ha='right')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
Result
The following program to analyze and plot a bar chart has been
successfully executed and obtained the output.
Output
6.Given the following data of rainfall in North and South zones
of india in mm for 12 months.
Zones Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
North 14 13 13 19 16 20 15 17 19 17 15 12
South 16 20 13 20 20 17 11 16 13 14 17 20
Aim:
To analyze and plot appropriate bar graphs to differentiate between
two given datas
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt
import numpy as np
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec']

north_rainfall = [14, 13, 13, 19, 16, 20, 15, 17, 19, 17, 15, 12]
south_rainfall = [16, 20, 13, 20, 20, 17, 11, 16, 13, 14, 17, 20]
x = np.arange(len(months))
width = 0.35
plt.figure(figsize=(10, 6))
plt.bar(x - width/2, north_rainfall, width, label='North Zone', color='blue')
plt.bar(x + width/2, south_rainfall, width, label='South Zone', color='black')
plt.xticks(ticks=x, labels=months)
plt.title('Monthly Rainfall (North vs. South)', fontsize=14)
plt.xlabel('Month', fontsize=12)
plt.ylabel('Rainfall (mm)', fontsize=12)
plt.legend()
plt.show()
Result
The following program to analyze and plot appropriate bar graphs to
differentiate between two given data has been successfully executed and
obtained the output.
Output
7.Write a program in Python Pandas to create the following DataFrame “df”
from a dictionary. Draw line charts to show the plotting of score1 and score2
for all batsmen. Put legends and titles. Specify different colors and line styles
of your choice for both plotted lines. Change font size of the titles to 15 and
color to green
B_No Name Score1 Score2 Location
1 M.S.Dhoni 95 80 Ranchi
2 Virat Kohli 85 92 Delhi
3 Sachin 110 75 Mumbai
4 Karthik 75 80 Delhi
Aim:
To create the following DataFrame “df” from a dictionary. draw line
charts to show the plotting of score1 and score2 for all batsmen
and put legends and titles
Software Required:
Spyder IDE
Program
import pandas as pd
import matplotlib.pyplot as plt
data = { "B_No": [1, 2, 3, 4],
"Name": ["M.S.Dhoni", "Virat Kohli", "Sachin", "Karthik"],
"Score1": [95, 85, 110, 75],
"Score2": [80, 92, 75, 80],
"Location": ["Ranchi", "Delhi", "Mumbai", "Delhi"]}
df = pd.DataFrame(data)
print("DataFrame:")
print(df)
plt.figure(figsize=(10, 6))
plt.plot(df["Name"], df["Score1"], label="Score1", color="blue",
linestyle="--", marker="o")
plt.plot(df["Name"], df["Score2"], label="Score2", color="red", linestyle="-",
marker="x")
Output
plt.title("Scores of Batsmen", fontsize=15, color="green")
plt.xlabel("Batsmen", fontsize=12)
plt.ylabel("Scores", fontsize=12)
plt.legend()
plt.tight_layout()
plt.grid(visible=True, linestyle="--", alpha=0.6)
plt.show()

Result
The following program To create the following DataFrame “df” from a
dictionary. draw line charts to show the plotting of score1 and
score2 for all batsmen and put legends and titles has been
successfully executed and obtained the output.
Output
8.Given the ages of 50 participants in some game.
Write a program to plot a histogram from give
data with 10 bins.
Data=[10,11,13,13,15,16,17,18,19,21,23,23,23,24,24,25,
25,25,25,25,26,26,27,27,27,27,29,30,30,30,30,31,33,34,3
4,35,36,36,37,37,37,38,39,40,40,40,41,42,43,43]

Aim:
to plot a histogram from give data with 10 bins
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt
data = [
10, 11, 13, 13, 15, 16, 17, 18, 19, 21, 23, 23, 23, 24, 24, 25, 25, 25, 25,
25,
26, 26, 27, 27, 27, 27, 29, 30, 30, 30, 30, 31, 33, 34, 34, 35, 36, 36, 37,
37,
37, 38, 39, 40, 40, 40, 41, 42, 43, 43]
plt.figure(figsize=(10, 6))
plt.hist(data, bins=10, color='orange', edgecolor='black', alpha=0.7)
plt.title('Age Distribution of Participants', fontsize=15, color='black')
plt.xlabel('Age Groups', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()

Result
The following program to plot a histogram from give data with 10 bins
has been successfully executed and obtained the output.
Output
9.Given below are the sugar levels for men and
women in a city.Compare the sugar levels amongst
them.
Men=[113,84,90,150,149,88,93,115,135,80,77,82,129]
Women=[67,98,89,120,133,150,84,69,89,79,120,112,100]

Aim:
to plot a histogram from give data.
Software Required:
Spyder IDE

Program
import matplotlib.pylab as plt

sugar_men = [113,85,90,150,149,88,93,115,135,80,77,82]
sugar_women = [67,98,89,120,133,150,84,69,79,120,112,100]

plt.title("Blood Sugar Analysis")


plt.hist([sugar_men,sugar_women],bins=[80,100,120,140,160], color=["red",
"blue"], label=["Men", "Women"])
plt.xlabel("Blood Sugar Range")
plt.ylabel("No. of Patients")
plt.legend()
plt.show()

Result
The following program to plot a histogram from give data has been
successfully executed and obtained the output.
Output
Topic:CSV Programs

10.Create a program for importing and exporting Data


between Pandas and CSV Files.
Aim:
to create a program for importing and exporting Data between
Pandas and CSV Files
Software Required:
Spyder IDE

Program

import pandas as pd

data = {

"Name": ["John", "Alice", "Bob", "Emma"],

"Age": [24, 28, 22, 26],

"City": ["New York", "Los Angeles", "Chicago", "Houston"],

"Salary": [70000, 80000, 60000, 75000]

df = pd.DataFrame(data)

csv_file = "sample_data.csv"

df.to_csv(csv_file, index=False)

print(f"DataFrame exported to '{csv_file}' successfully.\n")

imported_df = pd.read_csv(csv_file)

print("Imported DataFrame:")

print(imported_df)

Result

The following program to create a program for importing


and exporting Data between Pandas and CSV Files has
been successfully executed and obtained the output.
Output
11.Write a program to create and open a
DataFrame using “student_result.csv” file
using pandas,to display row labels,column
labels,shape(no of rows and columns)of the
csv file.

Aim:
to create and open a DataFrame using “student_result.csv” file
using pandas,to display row labels,column labels,shape(no of rows
and columns)of the csv file.
Software Required:
Spyder IDE
Program
import pandas as pd
data = {"Name": ["John", "Alice", "Bob", "Emma"],"Math": [85, 78, 92,
88],"Science": [90, 85, 87, 95],"English": [88, 90, 85, 92]}
student_results = pd.DataFrame(data)
csv_file = "student_result.csv"
student_results.to_csv(csv_file, index=False)
print(f"DataFrame exported to '{csv_file}' successfully.\n")
imported_df = pd.read_csv(csv_file)
print("Row Labels (Index):")
print(student_results.index)
print("\nColumn Labels:")
print(student_results.columns)
print("\nShape of the DataFrame (Number of Rows and Columns):")
print(student_results.shape)
Result
The following program to create and open a DataFrame using
“student_result.csv” file using pandas,to display row labels,column
labels,shape(no of rows and columns)of the csv file has been
successfully executed and
Output
12.Read a CSV file to create a DataFrame and do the
following operations:
To display name,gender and percentage from
file.
To display the first and last 2 rows from the file.
Aim:
to create a DataFrame and do operations on it
Software Required:
Spyder IDE
Program
import pandas as pd
data = {
"Name": ["John", "Alice", "Bob", "Emma", "Mike", "Sophia"],
"Gender": ["Male", "Female", "Male", "Female", "Male", "Female"],
"Percentage": [88.0, 84.3, 88.0, 91.7, 78.3, 87.3]
}
student_results = pd.DataFrame(data)
csv_file = "student_result.csv"
student_results.to_csv(csv_file, index=False)
print(f"DataFrame exported to '{csv_file}' successfully.\n")
print("Name, Gender, and Percentage columns:")
print(student_results[["Name", "Gender", "Percentage"]])
print("\nFirst 2 rows of the DataFrame:")
print(student_results.head(2))
print("\nLast 2 rows of the DataFrame:")
print(student_results.tail(2))
Result

The following program to create a DataFrame, to display


name,gender and percentage from file and to display the
first and last 2 rows from the file has been successfully
executed and obtained the output.
Topic:SQL Queries
1.Consider the following table named EXAM with
details of marks. Write command of MySQL for
(i) to (iv) and output for (v) to (vii).

i)To display all information of the students of


humanities in descending order of percentage.

ii)To display Adno,Name,Percentage and Stream of those


students whose name is less than 6 characters long.

iii)To add another column Bus_Fees with datatype and


size as Decimal(8,2).

iv)To increase percentage by 2% of all the Humanities


students.
v)SELECT COUNT(*) FROM EXAM;

vi)SELECT SName,Percentage FROM EXAM WHERE SName


LIKE “N%”;

vii)SELECT ROUND(Percentage,0) FROM EXAM WHERE


Adno=”R005”;
2.Consider the table SUPPLIER given below. Write commands
in MySQL for (i) to (ii) and output for (iii) to (v).

i)To count distinct City in the table.

ii)To insert a new row in the table SUPPLIER110,


“Bournvita”,’ ABC’, 170, ‘Delhi’, 40.00

iii)SELECT Pname FROM SUPPLIER WHERE Supname IN


('Bread', 'Maggi');
iv)SELECT COUNTCDISTINCT City) FROM SUPPLIER;

v) SELECT MAX(Price) FROM SUPPLIER WHERE City =


‘Kolkata’;
3.Consider the table SHOPEE given below. Write commands
in MySQL for (i) to (iv) and output for (v) to (vii).

i)To Display names of the product, whose name starts with “C”in
ascending order of Price

ii)To display code, product name and City of the products whose
quantity is less than 100

iii)To count distinct Company in the table

iv)To insert a new row in the table 110, ‘Pizza’, ‘Papa Jones’,
120, ‘Kolkata’, 50.00
v)SELECT Pname FROM SHOPEE WHERE Pname IN(“Jam”,”Coffee”);

vi)SELECT COUNT(DISTINCT City) FROM SHOPEE;

vii)SELECT MAX(Qty) FROM SHOPEE WHERE City=”Mumbai”;

4.Consider the table PERSONS given below. Write commands


in SQL for (i) to (iv) and write output for (v) to (viii).
i)Display the SurName, FirstName and
City of people residing in Udhamwara city.

ii)Display the Person IDs (PID), Cities and


Pincode of persons in descending order of
Pincode.

iii) Display the FirstName and City of all


the females getting Basic salaries above
40000
iv) Display FirstName and BasicSalaries of
all the persons whose first name start
with ‘G’

v) SELECT SurName FROM PERSONS WHERE


BasicSalary>= 50000;

vi) SELECT SUM (BasicSalary) FROM


PERSONS WHERE Gender = ‘F’;

vii)SELECT Gender, MIN (BasicSalary) FROM


PERSONS GROUP BY Gender;
viii) SELECT Gender, COUNT (*) FROM PERSONS GROUP BY
Gender;
5. Consider the EXAM table given below. Write commands in MySQL
for (i) to (iv) and output for (v) to (vii)

i)To list the Names of those students, who have obtained Division as
FIRST in ascending order of Name.

(ii) To display a report listing Name, Subject and Annual Stipend


received assuming that the Stipend column has monthly Stipend.
(iii) To count the number of students, who have either Accounts or
Informatics as Subject.

(iv) To insert a new row in the table EXAM. 6, ‘Mohan’, 500,


‘English’, 73, ‘SECOND’

(v) SELECT AVG(Stipend) FROM EXAM WHERE Division = ‘THIRD’;


(vi) SELECT COUNT (DISTINCT Subject) FROM EXAM;

(vii) SELECT MIN(Average) FROM EXAM WHERE Subject = ‘English’;


6. Consider the table DOCTOR given below. Write commands in SQL
for (i) to (iv) and output for (v) to (vii)

(i)Display the names and dates of joining of doctors of Oncology


department.

(ii) Display the names and salaries of doctors in descending order of


salaries.
(iii) Display the names and salaries of all the female’s doctors who
are getting salary above $ 50000.

(iv) Display names of each department along with total salary being
given to doctors of that department.

(v) SELECT Department FROM DOCTOR WHERE Salary >= 55000;

(vi) SELECT SUM (Salary) FROM DOCTOR WHERE Department =


‘Surgery’;
(vii) SELECT Doc_Name FROM DOCTOR WHERE Doc_Name LIKE ’J%’;
7. Consider the table LIBRARY given below. Write commands in
MySQL for (i) to (iv) and output for (v) to (vii)

(i)To list the BookTitle of FND type.

(ii) To display a report listing BookTitle, Type and Price in


descending order of price.

(iii) To count the number of BookTitle, Who have FND type.


(iv) To insert a new row in the table LIBRARY. 7, ‘Windows 8 Basics’,
‘FND’,’McGraw’, 7,150.

(v) SELECT AVG(Price) FROM LIBRARY WHERE Type = ‘FND’;

(vi) SELECT COUNT(DISTINCT Type) FROM LIBRARY;


8. Consider the table STUDENT given below. Write commands in
MySQL for (i) to (iv) and output for (v) to (vii)

(i)To list the StudentName of Science Stream.

(ii) To display a report listing StudentName, Class and Stream in


ascending order of StudentName.

(iii) To count the number of students to Science Stream.


(iv) To insert a new row in the table STUDENT. 7, ‘Simran Kaur’,’X!l’,
‘Commerce’, 86, ‘A2’

(v) SELECT AVG(AggMarks) FROM STUDENT WHERE


Stream=‘Science’;

(vi) SELECT COUNT (DISTINCT Stream) FROM STUDENT;

(vii) SELECT MIN(AggMarks) FROM STUDENT;


9. Consider the table PRODUCT given below. Write commands in
MySQL for (i) to (iv) and output for (v) to (vii)

(i)To list the ProductName where BrandName is Maharaja.

(ii) To display a report ProductName and BrandName and Price in


descending order of price.

(iii) To count the number of ProductName.


(iv) To insert a new row in the table PRODUCT. 6, ‘Gas
Stove’,’Maharaja’,7, 6150

(v) SELECT AVG(Price) FROM PRODUCT WHERE BrandName =


‘Maharaja’;

(vi) SELECT COUNT (DISTINCT BrandName) FROM PRODUCT;


(vii) SELECT MAX(Price) FROM PRODUCT;

10. Consider the table SPORTS given below. Write commands in


MySQL for (i) to (iv) and output for (v) to (vii)

(i)To list the Name of the students whose Game is Cricket.

(ii) To display a report listing Name, Game and Grade in ascending


order of name.
(iii) To count the number of students.

(iv) To insert a new row in the table SPORTS. 7, ‘Rishabh’, 9,


‘Cricket’, ‘A’
(v) SELECT Name, Game FROM SPORTS WHERE Name LIKE ‘k%‘,
(vi) SELECT COUNT (DISTINCT Game) FROM SPORTS;
(vii) SELECT Name, Game, Grade FROM SPORTS WHERE Grade = ‘B';
11. Consider the table INTERIORS given below. Write commands in
MySQL for (i) to (iv) and output for (v) to (vii)
(i)To list the ItemName whose Type is Office Table.

(ii) To display a report listing ItemName, Type and Price in


descending order of Price.
(iii) To count the number of ItemName.

(iv) To insert a new row in the table INTERIORS. 7, ‘Comfort


Zone’,’Double Bed’,’23/03/2011′, 15000

(v) SELECT ItemName, Type FROM INTERIORS WHERE ItemName LIKE


‘R%’;
(vi) SELECT COUNT (DISTINCT Type) FROM INTERIORS;
(vii) SELECT ItemName, Type FROM INTERIORS WHERE
DateofStock>‘15/ll/2010’;
15.

1.Create the table TEACHER with the following attributes and


records
2.Display all the information about the teachers of History
department whose name starts with the letter S
3.Display the names of female teachers who are in Math
department.
4.Display the names and departments of all teachers with their date
of joining in descending order.
5.Increase the salary by 500 for all teachers working in Computer
department.
6.Insert a new row in the teacher table with the following data.
[7,”Raj”,26,”Computer”,”1995-05-13”,20000,”M”]
7.Count the number of teachers with age>23
8.Display the different departments in the teacher table.
9.To remove all the teachers who joined after 1998.
10.Write a command to view the structure of the above table.
11.Write outputs for the following:
a.SELECT COUNT(DISTINCT DEPT)FROM TEACHER;
b.SELECT MAX(AGE) FROM TEACHER WHERE SEX=”F”;
c.SELECT AVG(SALARY) FROM TEACHER WHERE SEX=’M’;
d.SELECT NAME,AGE FROM TEACHER ORDER BY SALARY DESC;
17.

1.To display the names of patients in uppercase and departments in


lowercase for female patients in ENT
2.To return the second to fourth character from departments for all
male patients.
3.To list the position of character ‘A’ in the names of patients who
are aged over 50.
4.To display number and length of department and name of patient
in surgery department.

5.To display first four characters of department field who were


admitted before 2008.
6. To display month and year of admission of Karina.
7. Round of charges to 1 decimal places for all patients admitted in
1998 andwho are aged above 50.

8. Round the charges to nearest tens of all those in Cardiology


department in descending order of charges.
9. To display the first 4 characters of names in capitals and last 4
characters of deparment in small letters whose data of appointment
is JULY.
10. To display the name of month,day of month for all those Female
patients in surgery department.
11.To display all the names and departments of patients whose
name starts with A on descending order of the charges.
12.Write the output for the following queries.
a.SELECT MOD(27,4),SIGN(POW(-3,3));
b.SELECT ROUND(26.789,2),ROUND(45.34),ROUND(285.678,-2);
c.SELECT MONTHNAME(DOA),DAY(DOA) FROM HOSPITAL WHERE
DEPARTMENT<>’ENT’ OR NAME LIKE ‘%A’;
d.SELECT SUBSTR(NAME,2,4),INSTR(DEPARTMENT,’N’)FROM
HOSPITAL WHERE SEX=’F’;

You might also like