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

Python Programs

Python programming

Uploaded by

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

Python Programs

Python programming

Uploaded by

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

[1] Write a program to generate a series of float numbers from 41.0 to 60.

0 with an
increment of 2.5.

import pandas as pd
import numpy as np
n=np.arange(41,60,2.5)
s=pd.series(n)
print(s)

Output:

2 46.0
3 48.5
4 51.0
5 53.5
6 56.0
[2] Write a program to generate a series of 10 numbers with a scalar value of 44.

import pandas as pd
print(pd.Series(44,range(1,11)))

Output:

1 44
2 44
3 44
4 44
5 44
6 44
7 44
8 44
9 44
10 44
dtype: int64
[3] Create a panda’s series from a dictionary of values and a ndarray.

import pandas as pd
#creating series from a dictionary
d={'Jan':31,'Feb':28,'Mar':31,'Apr':30}
s=pd.series(d)
print('Series from dictionary')
print('~~~~~~~~~~~~~~~~~~~~~~~~~')
print(s)
#Creating series from an ndarray
ar=np.array([2,3,4,5,6])
print('\nSeries from ndarray')
print('~~~~~~~~~~~~~~~~~~~~~~~~')
s1=pd.Series(ar)
print(s1)

Output

Series from dictionary


~~~~~~~~~~~~~~~~~~~~~~~~~
Jan 31
Feb 28
Mar 31
Apr 30
dtype: int64

Series from ndarray


~~~~~~~~~~~~~~~~~~~~~~~~
0 2
1 3
2 4
3 5
4 6
dtype: int32
[4] Given a series,print all the elements that are above the 75th percentile.

import pandas as pd
std_marks=[]
for i in range(1,6):
m=int(input('Enter the Percentile:'))
std_marks.append(m)
s=pd.Series(index=range(1201,1206),data=std_marks)
print('Data fetched from the series are:')
print(s[s>=75])

Output:

Enter the Percentile: 63


Enter the Percentile: 78
Enter the Percentile: 52
Enter the Percentile: 88
Enter the Percentile :83
Data fetched from the series are:

1202 78
1204 88
1205 83
dtype: int64
[5] Create a data frame for examination results and display roe labels, column labels data
types of each column and the dimensions.

import pandas as pd
res={'Amit':[76,78,75,66,68],
'Shialesh':[78,56,77,49,55],
'Rani':[90,91,93,97,99],
'Madan':[55,48,59,60,66],
'Radhika':[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)
Printing row labels in a list:

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

[0, 1, 2, 3, 4]

Printing row labels in a list:

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

[ Amit ]

Printing Data Types of each column

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

Amit int64

Shialesh int64

Rani int64

Madan int64

Radhika int64

dtype: object

Printing dimensions of Data Frame

~~~~~~~~~~~~~~~~~~~~~~~~~
[6] Create a dataframe and iterate them over rows.

import pandas as pd
data=[["virat",55,66,31],["rohit",88,66,43],["hardik",99,101,68]]
players=pd.DataFrame(data,columns=["Name","Match-1","Match-2","Match-3"])
print("Iterating by rows:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
for index, rows in players.iterrows():
print(index,rows.values)
print("Iterating by columns:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
for index, rows in players.iterrows():
print(index,row["Name"],row["Match-1"],
row["Match-2"],row["Match-3"])

output:

Iterating by rows:

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

0 [ ‘virat’ 55 66 31]

1 [‘rohit’ 88 66 43]

2[‘hardik’ 99 101 68]

Iterating by columns:

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

0 virat 55 66 31

1 rohit 88 66 43

2 hardik 99 101 68
[7] Create a dataframe and print it along with their index using iteritems().

import pandas as pd

sc_4yrs={2016:{'Virat Kohli':2595,'Rohit Sharma':2406,'Shikhar Dhawan':2378},

2017:{'Virat Kohli':2818,'Rohit Sharma':2613,'Shikhar Dhawan':2295},

2018:{'Virat Kohli':2735,'Rohit Sharma':2406,'Shikhar Dhawan':2378},

2019:{'Virat Kohli':2455,'Rohit Sharma':2310,'Shikhar Dhawan':1844}}

df=pd.DataFrame(sc_4yrs)

print(df)

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

for (year,runs) in df.iteritems():

print("Year:",year)

print(runs)
OUTPUT:

Year: 2016

ViratKohli 2595

Rohit Sharma 2406

ShikharDhawan 2378

Name: 2016, dtype: int64

Year: 2017

ViratKohli 2818

Rohit Sharma 2613

ShikharDhawan 2295

Name: 2017, dtype: int64

Year: 2018

ViratKohli 2735

Rohit Sharma 2406

ShikharDhawan 2378

Name: 2018, dtype: int64


[8] 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.

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("Display column data types")


print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")

print(sales.dtypes)

print("Display the dimensions, shape, size and values of Sales")

print("~~~~~~~~~~~~~~~~~~~~~~~~~\n")

print("Dimensions:",sales.ndim)

print("Shape:",sales.shape)

print("Size:",sales.size)

print("Values:”,sales.values)
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)

Size: 16

Values: [[110 205 115 118]

[130 165 206 198]

[115 175 157 183]


[118 190 179 169]]
[9] Consider above DataFrame and write code to do the following:

1. Display the last two rows of Sales.


2. Display the first two columns of Sales.

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:])
#with specific columns,I have printed two columns
print("specific columns")
print(sales.iloc[-2:,-2:])
print("display first two columns of dataframe:")
print("---------------------------------------------")
print(sales[sales.columns[0:2]])
Output:

Display last two rows of Dataframe :

Using Tail Function :

2018 2019 2020 2021


Shikhar 115 175 187 187
Mohini 120 156 198 169

Using iloc

2018 2019 2020 2021


Shikhar 115 175 157 183
Mohini 118 190 179 163
Specific columns
2020 2021
Shikhar 157 183
Mohini 179 169

Display first two columns of dataframe:

2018 2019
Kapil 110 205
Kamini 130 165
Shikhar 115 175
Mohini 118 190
[10] Use above (Question 9) dataframe 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.
5.Delete the data for the year 2018 from the dataframe sales.
6.Delete the data for salesman shikhar from the dataframe sales.
7.Change the name of the salesperson Kamini to Rani and Kapil to Anil.
8.Update the sale made by Mohini in 118 to 150 in 2018.

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")
print(sales.loc[:,2018])
print("sales made by kapil and mohini:")
print(sales.loc[['kapil','mohini'],[2019,2020]])
print("add data:")
sales.loc["Nirali"]=[221,178,165,177]
print(sales)
print("Delete Data for 2018:")
sales=sales.drop(columns=2018)
print(sales)
sales.drop("kinshuk")
print(sales)
sales=sales.rename({"kamini":"rani","kapil":"anil"},axis="index")
print(sales)
sales.loc[sales.index=="Mohini",2018]=150
print(sales)
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

Sales made by kapil and mohini:


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

Delete data for 2018:


2019 2020 2021
Kapil 205 115 118
Kamini 165 206 156
Shikhar 156 167 177
Mohini 198 145 187
Nirali 178 174 198

2019 2020 2021


Kapil 205 456 118
Kamini 165 206 198
Shikhar 175 197 183
Mohini 190 567 178
Nirali 178 165 187

2019 2020 2021


Anil 205 115 118
Rani 165 206 198
Shikhar 175 197 176
Mohini 176 176 198
Nirali 190 167 198
2019 2020 2021 2018
Anil 205 134 145 176
Rani 145 197 186 134
Shikhar 187 167 197 153
Mohini 267 234 234 198
Nirali 223 123 123 198
[11]Plot the following data on a line chart and customize chart according to below
given instructions :

Month January February March April May


Sales 510 350 475 580 600

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 color for the line.

5.Use the line style-dashed.

6.Display diamond style markers on data points.

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:
[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 Mon Tues Wed Thus Fri


Cotton 450 560 400 605 580
Jeans 490 600 425 610 625

1. Write a title for the chart “the weekly garments orders”.


2. Write the appropriate titles of both the axes .
3. Write code to display legends.
4. Display your chice of colors for both the lines cotton and jeans.
5. Use the linestyle – dotted for cotton and dashdot for jeans.
6. Display plus markers on cotton and x markers of jeans.

import matplotlib.pyplot as pp

day=['mon','tues','wed','thurs','fri']

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()
OUTPUT:
[13].Observe the given data for monthly views of one of the youtube channels for six
months . Plot them on the line chart.

Month Jan Feb March April May June


Views 2500 2100 1700 3500 3000 3800

Apply the following customization 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 color for the line .

6. Use dot marker with blue edge color and black fill color.

import matplotlib.pyplot as pp

mon=['jan','feb','march','april','may','june']

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

pp.plot(mon,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()
OUTPUT:
14. Write a program to plot a range from 1to 30 with step value 4. Use the following
algebraic Exp y =5*x+2

import matplotlib.pyplot as pp

import numpy as np

x=np.arange(1,30,4)

y=5*x+2

pp.plot(x,y)

pp.show()

output
15. Display following bowling figure through bar chart :

Overs Runs
1 6
2 18
3 10
4 5

import matplotlib.pyplot as pp

overs=[1,2,3,4]

runs=[6,18,10,5]

pp.bar(overs,runs,color="m")

pp.xlabel("overs")

pp.ylabel("runs")

pp.title("Bowling Spell Analysis")

pp.show()

Output:
INDEX
PYTHON PROGRAMS
S.NO PRACTICAL SIGNATURE
1 Write a program to generate a series of float number from 41.0
to 60.0 with an increment of 2.5 each .
2 Write a program to generate a series of 10 numbers with a
scalar value of 44.
3 Create a pandas series from dictionary of values and a ndarray.
4 Given a series , print all the elements that are above the 75 th
percentile.
5 Create a dataframe for examination results and display row
labels , column labels datatypes of each columns and the
dimensions .
6 Create a dataframe and iterate them over rows.
7 Create a dataframe and print it along with their index using
iteritems().
8 Create the following dataframe sales containing year wise
sales figures for five sales persons in INR.Use the years as
column labels and sales person names.

9 Consider above dataframe and write code to do the following :


1. Display the last 2 rows of sales .
2. Display the first two columns of sales.
10 Use above dataframe 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 sales man nirali where the sales
made are [221,178,165,177,210] in the years
[2018,2019,2020,2021] respectively .
5. Delete the data for the year 2018 from the dataframe
sales.
6. Delete the data for salesman SHIKHAR from the
dataframe sales .
7. Change the names of the salesperson kamini to rani and
kapil to anil.
8. Update the sale made by mohini from 118 to 150 in
2018.

11. Plot the following data on a line chart and customize


chart according to below given instructions :
Month January February March April May
Sales 510 350 475 580 600
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 Mon Tues Wed Thus Fri
Cotton 450 560 400 605 580
Jeans 490 600 425 610 625
13. Observe the given data for monthly views of one of the
youtube channels for six months . Plot them on the line
chart.
Month Jan Feb March April May June
Views 2500 2100 1700 3500 3000 3800
14. Write a program to plot a range from 1to 30 with step
value 4. Use the following algebraic Exp y =5*x+2

15. Display following bowling figure through bar chart :

Overs Runs
1 6
2 18
3 10
4 5
ACKNOWLEDGEMENT

I wish to express my deep sense of gratitude and indebtedness to our learned teacher Ms.
PREETI, PGT(INFORMATICS PRACTICES), INDIAN MODERN SENIOR
SECONDARY SCHOOL for her valuable help , advice and guidance in the preparation of
this practical file.

I am also greatly indebted to our principal Mr. RAJENDER GAHLYAN and school
authorities for providing me with the facilities and requisite laboratory conditions for making
this practicle file.

I also extend my thanks to a number of teachers, my classmates and friends who helped
me to complete this practical file successfully.
CERTIFICATE

This is to certify that ____________ student of Class XII, INDIAN MODERN SENIOR
SECONDARY SCHOOL has completed the PRACTICAL FILE during the academic year
2023-24 towards partial fulfillment of credit for the Informatics Practices practical evaluation
of CBSE and submitted satisfactory report, as compiled in the following pages , under my
supervision.

External Examiner Internal Examiner

Signature Signature

You might also like