Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Practical Assignment Python

Practical assignment of python class 12 computer

Uploaded by

ayushkumars2007a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Practical Assignment Python

Practical assignment of python class 12 computer

Uploaded by

ayushkumars2007a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PRACTICAL ASSIGNMENT FILE 2022-23

(python
` Assignment No. 01
Write a program to generate a series of float numbers from 10.0 to 50.0
with an increment of 3.5 using user defined function.
Solution:-

import pandas as pd
import numpy as np
def series1():
array1 = np.arange(10,50,3.5)
s1 = pd.Series(array1)
print(s1)
series1()

Output:-

0 10.0
1 13.5
2 17.0
3 20.5
4 24.0
5 27.5
6 31.0
7 34.5
8 38.0
9 41.5
10 45.0
11 48.5
dtype: float64

Page No.:- 01
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 02

Write a program to generate a series of 10 numbers with a scalar value


of 44 with user defined index 1-10.

Solution:-

import pandas as pd

s1=pd.Series(44,range(1,11))

print(s1)

Output:-

Page No.:- 02
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 03
Create a panda’s series of five items from a dictionary, display 2nd and
3rd item and then 1st and 4th item of series.

Solution:-

import pandas as pd
import numpy as np
#Creating series from a dictionary
d={'Jan':31,'Feb':28,'Mar':31,'Apr':30,'may':31}
s=pd.Series(d)
print("Series from dictionary")
print("~~~~~~~~~~~~~~~~~~~~~~~")
print(s)
print("2nd and 3rd item of the series")# Slicing
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(s["Feb":"Mar"]) # using label
print(s[1:3]) # using index
print()
print("1st and 4th item of the series")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(s[["Jan","Apr"]]) # using label
print(s[[0,3]]) # using index

Page No.:- 03
PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Series from dictionary


~~~~~~~~~~~~~~~~~~~~~~~
Jan 31
Feb 28
Mar 31
Apr 30
may 31
dtype: int64
2nd and 3rd item of the series
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Feb 28
Mar 31
dtype: int64
Feb 28
Mar 31
dtype: int64

1st and 4th item of the series


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Jan 31
Apr 30
dtype: int64
Jan 31
Apr 30
dtype: int64

Page No.:- 04
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 04
Create a panda’s series of five items from an arrary, display 2nd and 3rd
item and then 1st and 4th item of the series.
Solution:-
import pandas as pd
import numpy as np
#Creating series from an ndarray
array1=np.array([2,3,4,5,6])
print("Series from ndarray")
print("~~~~~~~~~~~~~~~~~~~~~~~")
s1=pd.Series(array1)
print(s1)
print("2nd and 3rd item of the series")# Slicing
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(s1[1:3]) # using index
print()
print("1st and 4th item of the series")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(s1[[0,3]]) # using index

Page No.:- 05
PRACTICAL ASSIGNMENT FILE 2022-23
Output:-
Series from ndarray
~~~~~~~~~~~~~~~~~~~~~~~
0 2
1 3
2 4
3 5
4 6
dtype: int32
2nd and 3rd item of the series
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 3
2 4
dtype: int32

1st and 4th item of the series


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0 2
3 5
dtype: int32

Page No.:- 06
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 05

Create a data frame for examination results and display row labels,
column labels data types of each column and the dimensions.

Solution:-
import pandas as pd
res={'Gaurav':[76,78,75,66,68],
'Harsh':[78,56,77,49,55],
'Komal':[90,91,93,97,99],
'Radha':[55,48,59,60,66],
'Vyom':[78,79,85,88,86]}
df=pd.DataFrame(res)
print("Printing row labels in a list:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
idx=df.index
l=list(idx)
print(l)
print("Printing row labels in a list:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("[",end=" ")
for col in df.columns:
print(col,end=" ")
print("]")
print("Printing Data Types of each column")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(df.dtypes)
print("Printing dimensions of Data Frame")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(df.ndim)

Page No.:- 07
PRACTICAL ASSIGNMENT FILE 2022-23
Output:-
Gaurav Harsh Komal Radha Vyom

0 76 78 90 55 78

1 78 56 91 48 79

2 75 77 93 59 85

3 66 49 97 60 88

4 68 55 99 66 86

Printing row labels in a list:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

[0, 1, 2, 3, 4]

Printing row labels in a list:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

[ Gaurav Harsh Komal Radha Vyom ]

Printing Data Types of each column

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Gaurav int64

Harsh int64

Komal int64

Radha int64

Vyom int64

dtype: object

Printing dimensions of Data Frame

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Page No.:- 08
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 06
Create the following DataFrame Sales containing year wise sales figures for five
salespersons in INR. Use the years as column labels, and salesperson names as row
labels.
2018 2019 2020 2021
Kapil 110 205 177 189
Kamini 130 165 175 190
Shikhar 115 206 157 179
Mohini 118 198 183 169

1. Create the DataFrame.


2. Display the row labels of Sales.
3. Display the column labels of Sales.
4. Display the data types of each column of Sales.
5. Display the dimensions, shape, size and values of Sales.

Solution-
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118], 2019:[205,165,175,190],
2020:[115,206,157,179], 2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
#Display row labels
print("Row Labels:\n",sales.index)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
#Display column labels
print("Column Labels:\n",sales.columns)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
#Display data type
print("\nDisplay column data types")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(sales.dtypes)
print("\nDisplay the dimensions, shape, size and values of Sales")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Dimensions:",sales.ndim)
print("Shape:",sales.shape)
("Size:",sales.size)
print("Values:",sales.values)

Page No.:- 09
PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Row Labels:
Index(['Kapil', 'Kamini', 'Shikhar', 'Mohini'], dtype='object')
~~~~~~~~~~~~~~~~~~~~~~~~~~

Column Labels:
Int64Index([2018, 2019, 2020, 2021], dtype='int64')
~~~~~~~~~~~~~~~~~~~~~~~~~~

Display column data types


~~~~~~~~~~~~~~~~~~~~~~~~~~
2018 int64
2019 int64
2020 int64
2021 int64
dtype: object

Display the dimensions, shape, size and values of Sales


~~~~~~~~~~~~~~~~~~~~~~~~~~
Dimensions: 2
Shape: (4, 4)
Values: [[110 205 115 118]
[130 165 206 198]
[115 175 157 183]
[118 190 179 169]]

Page No.:- 010


PRACTICAL ASSIGNMENT FILE 2022-23

Assignment No. 07
Consider above sales dataframe and write code to display the last two
rows of Sales dataframe using different method.

Solution:-

import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print("Display last two rows of DataFrame:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

#Method 1
print("Using tail function:")
print(sales.tail(2))

#Method 2
print("Using iloc")
print(sales.iloc[-2:])

#method 3 With Columns


print("Sepcific Columns")
print(sales.iloc[-2:,-2:])

Page No.:- 011


PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Display last two rows of DataFrame:


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Using tail function:
2018 2019 2020 2021
Shikhar 115 175 157 183
Mohini 118 190 179 169
Using iloc
2018 2019 2020 2021
Shikhar 115 175 157 183
Mohini 118 190 179 169
Sepcific Columns
2020 2021
Shikhar 157 183
Mohini 179 169

Page No.:- 012


PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 08
Consider sales dataframe and write code to display the first two
columns of Sales dataframe using different methods.

Solution:-

import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
print("Display dataframe sales")
print(sales)
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])

print("Display first two columns of Dataframe:")


print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

#Method 1
print(sales[[2018,2019]])

#Method 2
print(sales[sales.columns[0:2]])

#Method 3
print(sales.iloc[:, 0:2] )

Page No.:- 013


PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Display dataframe sales


2018 2019 2020 2021
Kapil 110 205 115 118
Kamini 130 165 206 198
Shikhar 115 175 157 183
Mohini 118 190 179 169

Display first two columns of Dataframe:


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2018 2019
Kapil 110 205
Kamini 130 165
Shikhar 115 175
Mohini 118 190
2018 2019
Kapil 110 205
Kamini 130 165
Shikhar 115 175
Mohini 118 190
2018 2019
Kapil 110 205
Kamini 130 165
Shikhar 115 175
Mohini 118 190

Page No.:- 014


PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 09
Use above dataframe sales and do the following:
1. Change the DataFrame Sales such that it becomes its transpose.
2. Display the sales made by all sales persons in the year 2018.
3. Display the sales made by Kapil and Mohini in the year 2019 and
2020.
4. Add data to Sales for salesman Nirali where the sales made are
[221, 178, 165, 177, 210] in the years [2018, 2019, 2020, 2021]
respectively

Solution:-

import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print("Transpose:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(sales.T)
print("\nSales made by each salesman in 2018")
#Method 1
print(sales[2018])
#Method 2
print(sales.loc[:,2018])
print("Sales made by Kapil and Mohini:")
#Method 1
print(sales.loc[['Kapil','Mohini'], [2019,2020]])
#Method 2
print(sales.loc[sales.index.isin(["Kapil","Mohini"]),[2019,2020]])
print("Add Data:")
sales.loc["Nirali"]=[221, 178, 165, 177]
print(sales)

Page No.:- 015


PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Transpose:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Kapil Kamini Shikhar Mohini
2018 110 130 115 118
2019 205 165 175 190
2020 115 206 157 179
2021 118 198 183 169

Sales made by each salesman in 2018


Kapil 110
Kamini 130
Shikhar 115
Mohini 118
Name: 2018, dtype: int64
Kapil 110
Kamini 130
Shikhar 115
Mohini 118
Name: 2018, dtype: int64
Sales made by Kapil and Mohini:
2019 2020
Kapil 205 115
Mohini 190 179
2019 2020
Kapil 205 115
Mohini 190 179
Add Data:
2018 2019 2020 2021
Kapil 110 205 115 118
Kamini 130 165 206 198
Shikhar 115 175 157 183
Mohini 118 190 179 169
Nirali 221 178 165 177

Page No.:- 016


PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 10
Use above dataframe sales and do the following:
1. Delete the data for the year 2018 from the DataFrame Sales.
2. Delete the data for sales man Shikhar from the DataFrame Sales.
3. Change the name of the salesperson Kamini to Rani and Kapil to
Anil.
4. Update the sale made by Mohini in 118 to 150 in 2018.
Solution:-
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print(sales)

print("Delete Data for 2018:")


sales=sales.drop(columns=2018)
# Alternate method
#sales.drop(columns=2018,inplace=True)
print(sales)

sales=sales.drop("Shikhar",axis=0)
#sales.drop("shikhar")
print(sales)

sales=sales.rename({"Kamini":"Rani","Kapil":"Anil"},axis="index")
print(sales)

sales.loc[sales.index=="Mohini",2018]=150
print(sales)

Page No.:- 017


PRACTICAL ASSIGNMENT FILE 2022-23
Output:-
2018 2019 2020 2021
Kapil 110 205 115 118
Kamini 130 165 206 198
Shikhar 115 175 157 183
Mohini 118 190 179 169

Delete Data for 2018:


2019 2020 2021
Kapil 205 115 118
Kamini 165 206 198
Shikhar 175 157 183
Mohini 190 179 169

2019 2020 2021


Kapil 205 115 118
Kamini 165 206 198
Mohini 190 179 169

2019 2020 2021


Anil 205 115 118
Rani 165 206 198
Mohini 190 179 169

2019 2020 2021 2018


Anil 205 115 118 NaN
Rani 165 206 198 NaN
Mohini 190 179 169 150.0

Page No.:- 018


PRACTICAL ASSIGNMENT FILE 2022-23

Assignment No. 11
Plot the following data on a line chart and customize the chart
according to the below-given instructions:
Month January February March April May

Sales 510 350 475 580 600

Weekly Sales Report


1. Write a title for the chart “The Monthly Sales Report“
2. Write the appropriate titles of both the axes
3. Write code to Display legends
4. Display blue colour for the line
5. Use the line style – dashed
6. Display diamond style markers on data points

Solution:-

import matplotlib.pyplot as pp
mon =['January','February','March','April','May']
sales = [510,350,475,580,600]
pp.plot(mon,sales,label='Sales',color='b',linestyle='dashed',marker='D')
pp.title("The Monthly Sales Report")
pp.xlabel("Months")
pp.ylabel("Sales")
pp.legend()
pp.show()

output:-

Page No.:- 019


PRACTICAL ASSIGNMENT FILE 2022-23

Assignment No. 12
Pratyush Garments has recorded the following data into their register for their
income from cotton clothes and jeans. Plot them on the line chart.

Day Monday Tuesday Wednesday Thursday Friday

Cotton 450 560 400 605 580

Jeans 490 600 425 610 625

Apply following customization to the line chart.

1. Write a title for the chart “The Weekly Garment Orders”.


2. Write the appropriate titles of both the axes.
3. Write code to Display legends.
4. Display your choice of colours for both the lines cotton and jeans.
5. Use the line style – dotted for cotton and dashdot for jeans.
6. Display plus markers on cotton and x markers of jeans.

Solution:-

import matplotlib.pyplot as pp
day =['Monday','Tuesday','Wednesday','Thursday','Friday']
ct = [450,560,400,605,580]
js = [490,600,425,610,625]
pp.plot(day,ct,label='Cotton',color='g',linestyle='dotted',marker='+')
pp.plot(day,js,label='Food',color='m',linestyle='dashdot',marker='x')
pp.title("The Weekly Garment Orders")
pp.xlabel("Days")
pp.ylabel("Orders")
pp.legend()
pp.show()

Page No.:- 020


PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Page No.:- 021


PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 13

Observe the given data for monthly views of one of the youtube channels for 6
months. Plot them on the line chart.

Month January February March April May June

Views 2500 2100 1700 3500 3000 3800

Apply the following customizations to the chart:

1. Give the title for the chart – “Youtube Stats”


2. Use the “Month” label for X-Axis and “Views” for Y-Axis.
3. Display legends.
4. Use dashed lines with the width 5 point.
5. Use red colour for the line.
6. Use dot marker with blue edge colour and black fill colour.

Solution:-

import matplotlib.pyplot as pp

months=['January','February','March','April','May','June']

views=[2500,2100,1700,3500,3000,3800]

pp.plot(months,views,label='Views State',color='r',

linestyle='dashed', linewidth=4,

marker='o', markerfacecolor='k',

markeredgecolor='b')

pp.title("Youtube Stats")

pp.xlabel("Months")

pp.ylabel("Views")

pp.legend()

pp.show()

Page No.:- 022


PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Page No.:- 023


PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 14

Smile NGO has participated in a three week cultural mela. Using


Pandas, they have stored the sales (in Rs) made day wise for every week
in a CSV file named “MelaSales.csv”, as shown

Week1 Week2 Week3


5000 4000 4000
5900 3000 5800
6500 5000 3500
3500 5500 2500
4000 3000 3000
5300 4300 5300
7900 5900 6000
Depict the sales for the three weeks using a Line chart. It should have
the following:

i. Chart title as “Mela Sales Report”.


ii. axis label as Days.
iii. axis label as “Sales in Rs”. Line colours are red for week 1, blue
for week 2 and brown for week 3.

Solutions:-

import pandas as pd
import matplotlib.pyplot as plt
# reads "MelaSales.csv" to df by giving path to the file
df=pd.read_csv("MelaSales.csv")
#create a line plot of different color for each week
df.plot(kind='line', color=['red','blue','brown'])
# Set title to "Mela Sales Report"
plt.title('Mela Sales Report')
# Label x axis as "Days"
plt.xlabel('Days')
# Label y axis as "Sales in Rs"
plt.ylabel('Sales in Rs')
#Display the figure
plt.show()

Page No.:- 024


PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Page No.:- 025


PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 15

Write a Python script to display Bar plot for the “MelaSales.csv” file with column Day on x axis,
and having the following customisation:
● Changing the color of each bar to red, yellow and purple.
● Edgecolor to green
● Linewidth as 2
● Line style as "--"
File name : MelaSales.csv
Week1 Week2 Week3 Day
5000 4000 4000 Monday
5900 3000 5800 Tuesday
6500 5000 3500 Wednesday
3500 5500 2500 Thursday
4000 3000 3000 Friday
5300 4300 5300 Saturday
7900 5900 6000 Sunday

Solution:-

import pandas as pd
import matplotlib.pyplot as plt
df= pd.read_csv('MelaSales.csv')
# plots a bar chart with the column "Days" as x axis
df.plot(kind='bar',x='Day',title='Mela Sales Report',color=['red',
'yellow','purple'],edgecolor='Green',linewidth=2,linestyle='--')
#set title and set ylabel
plt.ylabel('Sales in Rs')
plt.show()

Page No.:- 026


PRACTICAL ASSIGNMENT FILE 2022-23
Output:-

Page No.:- 027


PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 16

Display histogram of data provided for height and weight of few persons
in dataframe.

Name Arnav Sheela Azhar Bincy Yash Nazar


Height 60 61 63 65 61 60
Weight 47 89 52 58 50 47

Solution:-

import pandas as pd
import matplotlib.pyplot as plt
data = {'Name':['Arnav', 'Sheela', 'Azhar', 'Bincy', 'Yash','Nazar'],
'Height' : [60,61,63,65,61,60],
'Weight' : [47,89,52,58,50,47]}

df=pd.DataFrame(data)
df.plot(kind='hist')
plt.show()

Output:-

Page No.:- 028

You might also like