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

Class XII Python Practical File

Uploaded by

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

Class XII Python Practical File

Uploaded by

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

PROGRAM 1: Write a program to create Data Series and then change the

indices of the Series object in any random order.

import pandas as pd

Series_1=pd.Series(data=[100,200,300,400,500,600],
index=['A','B','C','D','E','F'])
print("#### ORIGINAL DATA SERIES ####")
print(Series_1)

Series_1=Series_1.reindex(index=['E','F','C','D','A','B'])

print("#### DATA SERIES AFTER CHANGING THE ORDER OF INDEX:


####")
print(Series_1)

Output:

#### ORIGINAL DATA SERIES ####


A 100
B 200
C 300
D 400
E 500
F 600
dtype: int64

#### DATA SERIES AFTER CHANGING THE ORDER OF INDEX: ####


E 500
F 600
C 300
D 400
A 100
B 200
dtype: int64

PROGRAM 2: Write a program to perform Arithmetic Operations on


Series…

import pandas as pd
ds1 = pd.Series([20,40,60,80,100])
ds2 = pd.Series([10,30,50,70,90])
print('Values of series ds1',ds1.values)
print('Values of series ds2',ds2.values)
print('##########################################
###########')
print('######Arithmetic Operations##########')
print()
ds3 = ds1 + ds2
print("##Addition of two Series##")
print(ds3.values)
print()
ds4 = ds1 - ds2
print("##Subtraction of two Series##")
print(ds4.values)
print()
ds5 = ds1 * ds2
print("##Product of two Series##")
print(ds5.values)
print()
ds6 = ds1 / ds2
print("##Divide Series1 by Series2##")
print(ds6.values)

Output:

Values of series ds1 [ 20 40 60 80 100]


Values of series ds2 [10 30 50 70 90]
#############################################
########
######Arithmetic Operations##########

##Addition of two Series##


[ 30 70 110 150 190]

##Subtraction of two Series##


[10 10 10 10 10]

##Product of two Series##


[ 200 1200 3000 5600 9000]

##Divide Series1 by Series2##


[2. 1.33333333 1.2 1.14285714 1.11111111]
PROGRAM 3: Write a program to implement Series attributes…

import pandas as pd
import numpy as np
s1 = pd.Series([10,20,30,40,50,60,70,80,90,100])
s2 = pd.Series([3,5,7,9,11,13,15,np.NaN], dtype='float32')
s3 = pd.Series([])
print('Values of the Series s1:',s1.values)
print('index of the Series s1:',s1.index)
print('Size of the Series s1:',s1.size)
print('Number of bytes in s1:',s1.nbytes)
print('Check for emptyness in s1:', s1.empty)
print('Check for NaNs in s1:', s1.hasnans)
print('Dtype of the objects:',s1.dtype)
print('##########################################
##')
print('Values of the Series s2:',s2.values)
print('index of the Series s2:',s2.index)
print('Size of the Series s2:',s2.size)
print('Number of bytes in s2:',s2.nbytes)
print('Check for emptyness in s2:', s2.empty)
print('Check for NaNs in s2:', s2.hasnans)
print('Dtype of the objects:',s2.dtype)
print('##########################################
#')
print('Values of the Series s3:',s3.values)
print('index of the Series s3:',s3.index)
print('Size of the Series s3:',s3.size)
print('Number of bytes in s3:',s3.nbytes)
print('Check for emptyness in s3:',s3.empty)
print('Check for NaNs in s3:', s3.hasnans)
print('Dtype of the objects:',s3.dtype)
print('##########################################
#')

Output:

Values of the Series s1: [ 10 20 30 40 50 60 70 80 90 100]


index of the Series s1: RangeIndex(start=0, stop=10, step=1)
Size of the Series s1: 10
Number of bytes in s1: 80
Check for emptyness in s1: False
Check for NaNs in s1: False
Dtype of the objects: int64
############################################
Values of the Series s2: [ 3. 5. 7. 9. 11. 13. 15. nan]
index of the Series s2: RangeIndex(start=0, stop=8, step=1)
Size of the Series s2: 8
Number of bytes in s2: 32
Check for emptyness in s2: False
Check for NaNs in s2: True
Dtype of the objects: float32
###########################################
Values of the Series s3: []
index of the Series s3: RangeIndex(start=0, stop=0, step=1)
Size of the Series s3: 0
Number of bytes in s3: 0
Check for emptyness in s3: True
Check for NaNs in s3: False
Dtype of the objects: float64
###########################################

PROGRAM 4: Write a Pandas program to find out the biggest and


smallest three area from given series that stores the area of some
states in km2 using Head/Tail function…

import pandas as pd

ser=
pd.Series([3456,890,450,67892,34677,78902,56711,68291,637632,257
23,236,1189,345,256517])
print("Area of Cities: ")
print(ser.values)
print('###############################')
print('Top 4 Biggest area are:-')
print(ser.sort_values(ascending=False).head(4))
print('Top 4 Smallest area are:-')
print(ser.sort_values(ascending=False).tail(4))

Output:

Area of Cities:
[ 3456 890 450 67892 34677 78902 56711 68291 637632
25723
236 1189 345 256517]
###############################
Top 4 Biggest area are:-
8 637632
13 256517
5 78902
7 68291
dtype: int64
Top 4 Smallest area are:-
1 890
2 450
12 345
10 236
dtype: int64

PROGRAM 5: Write a Pandas program to implement Series Slicing…

import pandas as pd
s1=pd.Series(range(1,20,2),index=(x for x in "abcdefghij"))
print("#### PROGRAM TO IMPLEMENT SERIES SLICING ####")
print("#### COMPLETE SERIES IS ####")
print(s1)
print("#### ELEMENT AT INDEX 5 IS ####")
print(s1[5])
s1.index=['p','q','r','s','t','u','v','w','x','y']
print("#### FIRST 6 ELEMENTS ARE ####")
print(s1[0:6])
print("#### AFTER MODIFICATION, 6TH ELEMENT OF GIVEN
SERIES IS ####")
s1[5]=90
print(s1[5])

Output:

#### PROGRAM TO IMPLEMENT SERIES SLICING ####


#### COMPLETE SERIES IS ####
a 1
b 3
c 5
d 7
e 9
f 11
g 13
h 15
i 17
j 19
dtype: int64
#### ELEMENT AT INDEX 5 IS ####
11
#### FIRST 6 ELEMENTS ARE ####
p 1
q 3
r 5
s 7
t 9
u 11
dtype: int64
#### AFTER MODIFICATION, 6TH ELEMENT OF GIVEN SERIES IS ####
90

PROGRAM 6: Write a Pandas program to Population of Four


metro cities of india and AvgIncome. Calculate income per capita
for each of these metro cities.

import pandas as pd
population =
pd.Series([1020010,19821121,2435533,34555252],index=['Delhi','kolkat
a','mumbai','chennei'])
AvgIncome =
pd.Series([346356543543,659656966596,56656565586,99569669969],i
ndex=['Delhi','kolkata','mumbai','chennei'])
percap=AvgIncome/population
print('####Population in four metroes####')
print(population)
print()
print('####AvgIncome in four metroes####')
print(AvgIncome)
print()
print('####Percapital income of four metroes####')
print(round(percap,2))

Output:

####Population in four metroes####


Delhi 1020010
kolkata 19821121
mumbai 2435533
chennei 34555252
dtype: int64
####AvgIncome in four metroes####
Delhi 346356543543
kolkata 659656966596
mumbai 56656565586
chennei 99569669969
dtype: int64

####Percapital income of four metroes####


Delhi 339561.91
kolkata 33280.51
mumbai 23262.49
chennei 2881.46
dtype: float64

Program 7: Program to implement DataFrame attributes…

import pandas as pd
toppersA={'Roll No':115,'Name':'Pavni','Marks':98}
toppersB={'Roll No':236,'Name':'Riya','Marks':99}
toppersC={'Roll No':307,'Name':'Preeti','Marks':97}
toppersD={'Roll No':422,'Name':'Shreya','Marks':98}

toppers=[toppersA,toppersB,toppersC,toppersD]

topDF1=pd.DataFrame(toppers,index=["Sec A","Sec B","Sec C","Sec D"])


print(topDF1)

val=topDF1.values
index=topDF1.index
col=topDF1.columns
axes=topDF1.axes
dt=topDF1.dtypes
dfsize=topDF1.size
dfshape=topDF1.shape
dfndim=topDF1.ndim
dfempty=topDF1.empty

print("Values of DataFrame:",val)
print()
print("The Row Labels of DataFrame:",index)
print()
print("The Column Labels of DataFrame:",col)
print()
print("The Row and Column Labels of DataFrame:",axes)
print()
print("Datatype of data of DataFrame:",dt)
print()
print("Number of elements of DataFrame:",dfsize)
print()
print("Shape of the DataFrame:",dfshape)
print()
print("Number of axes of DataFrame:",dfndim)
print()
print("Checking emptyness of DataFrame:",dfempty)

Output:

Marks Name Roll No


Sec A 98 Pavni 115
Sec B 99 Riya 236
Sec C 97 Preeti 307
Sec D 98 Shreya 422

Values of DataFrame: [[98 'Pavni' 115]


[99 'Riya' 236]
[97 'Preeti' 307]
[98 'Shreya' 422]]

The Row Labels of DataFrame: Index(['Sec A', 'Sec B', 'Sec C', 'Sec D'],
dtype='object')

The Column Labels of DataFrame: Index(['Marks', 'Name', 'Roll No'],


dtype='object')

The Row and Column Labels of DataFrame: [Index(['Sec A', 'Sec B', 'Sec
C', 'Sec D'], dtype='object'), Index(['Marks', 'Name', 'Roll No'],
dtype='object')]

Datatype of data of DataFrame: Marks int64


Name object
Roll No int64
dtype: object

Number of elements of DataFrame: 12


Shape of the DataFrame: (4, 3)

Number of axes of DataFrame: 2

Checking emptyness of DataFrame: False

Program 8: Program to find subset of DataFrame using loc and iloc


function…

import pandas as pd
data={'State':['Andhra','odisha','bihar','jharkhand','W.B'],
'Toys':[4656,5767,6784,1243,5766],
'Books':[34445,45554,45848,56574,56575],
'Uniform':[100,500,500,488,399],
'Shoes':[400,600,688,700,456]}
df=pd.DataFrame(data,columns=['State','Toys','Books','Uniform','Shoes']
)
print(df)
print('*********************************************')
print('A. Show data of Toys Column')
print(df['Toys'])
print('*********************************************')
print('B. Show data of First 3 rows Toys and Book columns (using loc)')
print(df.loc[0:3,['Toys','Books']])
print('*********************************************')
print('C. Show data of First 2 rows State,Toys and Books columns (using
iloc)')
print(df.iloc[0:2,0:3])

Output:

State Toys Books Uniform Shoes


0 Andhra 4656 34445 100 400
1 odisha 5767 45554 500 600
2 bihar 6784 45848 500 688
3 jharkhand 1243 56574 488 700
4 W.B 5766 56575 399 456
*********************************************
A. Show data of Toys Column
0 4656
1 5767
2 6784
3 1243
4 5766
Name: Toys, dtype: int64
*********************************************
B. Show data of First 3 rows Toys and Book columns (using loc)
Toys Books
0 4656 34445
1 5767 45554
2 6784 45848
3 1243 56574
*********************************************
C. Show data of First 2 rows State,Toys and Books columns (using iloc)
State Toys Books
0 Andhra 4656 34445
1 odisha 5767 45554

Program 9: Program to perform Binary Operations on DataFrame…

import pandas as pd

data={'A':{'1':35,'2':56,'3':33},\
'B':{'1':55,'2':46,'3':67},\
'C':{'1':90,'2':78,'3':78}}
df1=pd.DataFrame(data)
print(df1)
data={'A':{'1':45,'2':12,'3':3},\
'B':{'1':85,'2':90,'3':77},\
'C':{'1':90,'2':78,'3':8}}
df2=pd.DataFrame(data)
print(df2)
print()

print("#### ADITION OF DATAFRAMES ####")


print(df1+df2)
print()

print("#### SUBTRACTION OF DATAFRAMES ####")


print(df1-df2)
print()

print("#### MULTIPLICATION OF DATAFRAMES ####")


print(df1*df2)
print()
print("#### DIVISION OF DATAFRAMES ####")
print(df1/df2)

Output:

A B C
1 35 55 90
2 56 46 78
3 33 67 78
A B C
1 45 85 90
2 12 90 78
3 3 77 8

#### ADITION OF DATAFRAMES ####


A B C
1 80 140 180
2 68 136 156
3 36 144 86

#### SUBTRACTION OF DATAFRAMES ####


A B C
1 -10 -30 0
2 44 -44 0
3 30 -10 70

#### MULTIPLICATION OF DATAFRAMES ####


A B C
1 1575 4675 8100
2 672 4140 6084
3 99 5159 624

#### DIVISION OF DATAFRAMES ####


A B C
1 0.777778 0.647059 1.00
2 4.666667 0.511111 1.00
3 11.000000 0.870130 9.75

Program 10: Program to implement head() and tail() on DataFrame…

import pandas as pd
toppersA={'Roll No':115,'Name':'Pavni','Marks':98}
toppersB={'Roll No':236,'Name':'Riya','Marks':99}
toppersC={'Roll No':307,'Name':'Preeti','Marks':97}
toppersD={'Roll No':422,'Name':'Shreya','Marks':98}

toppers=[toppersA,toppersB,toppersC,toppersD]

df=pd.DataFrame(toppers,index=["Sec A","Sec B","Sec C","Sec D"])

print("Our data frame is:")


print(df)
print('##########################################
##')
print("The first two rows of the data frame is:")
print("----------------------------------------")
print(df.head(2))
print()
print("The last two rows of the data frame is:")
print("----------------------------------------")
print(df.tail(2))

Output:

Our data frame is:


Marks Name Roll No
Sec A 98 Pavni 115
Sec B 99 Riya 236
Sec C 97 Preeti 307
Sec D 98 Shreya 422
############################################
The first two rows of the data frame is:
----------------------------------------
Marks Name Roll No
Sec A 98 Pavni 115
Sec B 99 Riya 236

The last two rows of the data frame is:


----------------------------------------
Marks Name Roll No
Sec C 97 Preeti 307
Sec D 98 Shreya 422

Program 11: Program to implement Boolean Indexing…

import pandas as pd
toppersA={'Roll No':115,'Name':'Pavni','Marks':98}
toppersB={'Roll No':236,'Name':'Riya','Marks':99}
toppersC={'Roll No':307,'Name':'Preeti','Marks':97}
toppersD={'Roll No':422,'Name':'Shreya','Marks':98}

toppers=[toppersA,toppersB,toppersC,toppersD]

df1=pd.DataFrame(toppers,index=["Sec A","Sec B","Sec C","Sec D"])


print(df1)

sh=df1['Marks']>=98
print("#### DataFrame after applying Boolean Indexing ####")
print(df1[sh])

Output:

Marks Name Roll No


Sec A 98 Pavni 115
Sec B 99 Riya 236
Sec C 97 Preeti 307
Sec D 98 Shreya 422
#### DataFrame after applying Boolean Indexing ####
Marks Name Roll No
Sec A 98 Pavni 115
Sec B 99 Riya 236
Sec D 98 Shreya 422

Program 12: Program to implement Dataframe Rowwise…

import pandas as pd
disales={'Year1':{'Qtr1':34500,'Qtr2':56000,'Qtr3':47000,'Qtr4':49000},
\
'Year2':{'Qtr1':44900,'Qtr2':46100,'Qtr3':57000,'Qtr4':59000},\
'Year3':{'Qtr1':54500,'Qtr2':51000,'Qtr3':57000,'Qtr4':58500},\
'Year4':{'Qtr1':42900,'Qtr2':52100,'Qtr3':49000,'Qtr4':54000}}
df1=pd.DataFrame(disales)

for(row,rowSeries) in df1.iterrows():
print("Row Index:",row)
print("Containing:")
i=0
for val in rowSeries:
print("At",i,"position",val)
i=i+1

Output:

Row Index: Qtr1


Containing:
At 0 position 34500
At 1 position 44900
At 2 position 54500
At 3 position 42900
Row Index: Qtr2
Containing:
At 0 position 56000
At 1 position 46100
At 2 position 51000
At 3 position 52100
Row Index: Qtr3
Containing:
At 0 position 47000
At 1 position 57000
At 2 position 57000
At 3 position 49000
Row Index: Qtr4
Containing:
At 0 position 49000
At 1 position 59000
At 2 position 58500
At 3 position 54000

Program 13: Program to implement Dataframe Column wise…

import pandas as pd
disales={'Year1':{'Qtr1':34500,'Qtr2':56000,'Qtr3':47000,'Qtr4':49000},\
'Year2':{'Qtr1':44900,'Qtr2':46100,'Qtr3':57000,'Qtr4':59000},\
'Year3':{'Qtr1':54500,'Qtr2':51000,'Qtr3':57000,'Qtr4':58500},\
'Year4':{'Qtr1':42900,'Qtr2':52100,'Qtr3':49000,'Qtr4':54000}}
df1=pd.DataFrame(disales)

for(col,colSeries) in df1.iteitems():
print("Column Index:",col)
print("Containing:")
print(colSeries)

Output:
Column Index: Year1
Containing:
Qtr1 34500
Qtr2 56000
Qtr3 47000
Qtr4 49000
Name: Year1, dtype: int64
Column Index: Year2
Containing:
Qtr1 44900
Qtr2 46100
Qtr3 57000
Qtr4 59000
Name: Year2, dtype: int64
Column Index: Year3
Containing:
Qtr1 54500
Qtr2 51000
Qtr3 57000
Qtr4 58500
Name: Year3, dtype: int64
Column Index: Year4
Containing:
Qtr1 42900
Qtr2 52100
Qtr3 49000
Qtr4 54000
Name: Year4, dtype: int64

Program 14: Program to implement Data Visualization using Line chart

import matplotlib.pyplot as plt

names=["Ankita","Payal","Rohan","Charu"]
marks=[89,90,87,78]

plt.plot(names,marks)
plt.show()

years=[2002,2004,2006,2008,2010]
sales=[6700,6500,7800,8300,7900]
production=[8000,8200,8700,9000,8800]
plt.figure(figsize = (5,5))
plt.plot(years,sales,'g',linewidth=5,linestyle='dashdot')
plt.plot(years,production,'r',linewidth=8,linestyle='dashed')

plt.grid(True)
plt.xlabel("Years")
plt.ylabel("Sales")
plt.show()

Output:

Program 15: Program to implement Data Visualization using Bar Chart

import matplotlib.pyplot as plt

cities=["Delhi","Mumbai","Banglore","Hyderabad"]
population=[2256789,2749876,2419875,1953688]
clrs=['r','b','m','g']
plt.bar(cities,population,width=[0.6,1,0.8,0.5],color=clrs)
plt.show()
plt.barh(cities,population)
plt.xlabel("City")
plt.ylabel("Population")
plt.title("Population Comparison in different cities")

plt.show()

Output:
Program 16: Program to implement Data Visualization using Histogram…
import matplotlib.pyplot as plt

ages=[3,3,3,4,5,6,8,9,10,10,10,11,12,12]
plt.hist(ages,bins=5)
plt.show()

Output:

Program 17: Program to export file from DataFrame to csv file...

import pandas as pd
student={'Name':['Rinku','Ritu','Ajay','Pankaj','Aditya'],
'English':[67,78,75,88,92],'Physics':[78,67,98,90,86],
'IP':[78,88,98,89,90],'Maths':[79,86,91,79,83]}

dfstu=pd.DataFrame(student)
print(dfstu)

dfstu.to_csv("student.csv")
print("Data is exported to csv file")

Output:
Name English Physics IP Maths
0 Rinku 67 78 78 79
1 Ritu 78 67 88 86
2 Ajay 75 98 98 91
3 Pankaj 88 90 89 79
4 Aditya 92 86 90 83

Data is exported to csv file


student.csv

,Name,English,Physics,IP,Maths
0,Rinku,67,78,78,79
1,Ritu,78,67,88,86
2,Ajay,75,98,98,91
3,Pankaj,88,90,89,79
4,Aditya,92,86,90,83

Program 18: Program to read data from a csv file...


import pandas as pd
df1=pd.read_csv("student.csv",skiprows=1,names=["Stu Name","Sub
1","Sub 2","Sub 3","Sub 4"])
print(df1)

Output:
Stu Name Sub 1 Sub 2 Sub 3 Sub 4
0 Rinku 67 78 78 79
1 Ritu 78 67 88 86
2 Ajay 75 98 98 91
3 Pankaj 88 90 89 79
4 Aditya 92 86 90 83

You might also like