Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Class XII Practical File Part 1

Program 1
Creating a DataFrame
Write a python program to create a DataFrame for students storing their roll no, name,
address, phone and display the DataFrame on the screen.

Program
import pandas as pd
#insert the panda library
df=pd.DataFrame()
#creating an empty dataframe
df['rollno']=[1,2,3,4,5]
#declaring and initializing rollno
df['name']=['Bhavika','Mansha','Kriti','Drishti','Khushboo']
#declaring and initializing name
df['address']=['Punjabi Bagh','Moti Nagar','Ramesh Nagar','Kirti Nagar','Shadipur']
#declaring and initializing address
df['phone']=[2345,4567,8910,1112,1213]
#declaring and initializing phone no
print(df)
#print the DataFrame

Output
rollno name address phone
0 1 Bhavika Punjabi Bagh 2345
1 2 Mansha Moti Nagar 4567
2 3 Kriti Ramesh Nagar 8910
3 4 Drishti Kirti Nagar 1112
4 5 Khushboo Shadipur 1213
Program 2
Creating a series using dictionary and array of values
Write a python program to create a pandas series from a dictionary of values and ndarray.

Program
import pandas as pd
import numpy as np
#insert the pandas and numpy library
dict1=np.array([1,2,3,4,5,6,7])#declaring array
df1=pd.Series(dict1)#putting array in series
print("Printing series using array")
print(df1)
#declaring dictionary
dict2={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven'}
df2=pd.Series(dict2)#putting dictionary in series
print("Printing series using dictionary")
#print the DataFrame
print(df2)

Output
Printing series using array
01
12
23
34
45
56
67
dtype: int32
Printing series using dictionary
1 one
2 two
3 three
4 four
5 five
6 six
7 seven
dtype: object
Program 3
Write a python program to create a DataFrame quarterly sales where each row contains the
item category, item name and expenditure. Group the rows by the category and print the
total expenditure per category.

Program
import pandas as pd
df=pd.DataFrame()
df['item category']=['c1','c2','c3','c4']
df['item name']=['pen','pencil','bottle','lunchbox']
df['expenditure']=[1000,2000,3000,4000]
print(df)
p1=df.pivot_table(index='item category',values='expenditure',aggfunc=sum)
print(p1)

Output
item category item name expenditure
0 c1 pen 1000
1 c2 pencil 2000
2 c3 bottle 3000
3 c4 lunchbox 4000
Item category expenditure
c1 1000
c2 2000
c3 3000
c4 4000
Program 4
Write a python program to create a DataFrame for examination result and display row
labels, column labels data types of each column and the dimensions.

Program
import pandas as pd
df=pd.DataFrame()
df['Name']=['A','B','C','D']
df['Class']=[12,10,11,12]
df['Mrks1']=[88,85,89,90]
df['Mrks2']=[55,67,97,87]
df['Mrks3']=[77,75,74,73]
print(df)
print(df['Name'].shape)

Output
Name Class Mrks1 Mrks2
Mrks3
0 A 12 88 55 77
1 B 10 85 67 75
2 C 11 89 97 74
3 D 12 90 87 73
Program 5
Write a python program to create a Series Object

Program
import pandas as pd
mySeries = pd.Series([10,20,30])
# Creating a Series Object suing custom index
mySeries1 = pd.Series([10,20,30],index=[5,6,7])
print(mySeries)
print(mySeries1)
# Adding two Series Objects
print(mySeries+mySeries)

Output
0 10
1 20
2 30
dtype: int64
5 10
6 20
7 30
dtype: int64
0 20
1 40
2 60
dtype: int64
Program 6
Write a python program to show the use of header and tail methods of Series

Program
import pandas as pd
myDict= {1:'Mannat',2:'Samidha',3:'Jai',4:'Kalk',5:'Abhishek',6:'Yuvesh'}
print(myDict)
mySeries=pd.Series(myDict)
print(mySeries)
# By default head() function will print top five elements
print(mySeries.head())
# By default tail() function will print last five elements
print(mySeries.tail())

Output
{1: 'Mannat', 2: 'Samidha', 3: 'Jai', 4: 'Kalk', 5: 'Abhishek', 6: 'Yuvesh'}
1 Mannat
2 Samidha
3 Jai
4 Kalk
5 Abhishek
6 Yuvesh
dtype: object
1 Mannat
2 Samidha
3 Jai
4 Kalk
5 Abhishek
dtype: object
2 Samidha
3 Jai
4 Kalk
5 Abhishek
6 Yuvesh
dtype: object
Program 7
Write a python program to show the use of where condition using Series

Program
import pandas as pd
myDict= {1:10,2:20,3:30}
myDict2= {1:'Ajay',2:'Dheeraj',3:'Shanku'}
print(myDict)
mySeries=pd.Series(myDict)
mySeries2=pd.Series(myDict2)
print(mySeries)
# Simple where condition
print(mySeries.where(mySeries > 10))
print(mySeries.where(mySeries < 20))
print(mySeries.where(mySeries == 10))
#The where() function is used to replace values where the condition is False.
print(mySeries.where(mySeries == 10,33))
#The where() function is used to replace values where the condition is False.
print(mySeries.where(mySeries != 10,33))
print(mySeries2)
# Simple where condition
print(mySeries2.where(mySeries2 == 'Ajay'))
print(mySeries2.where(mySeries2 != 'Ajay'))
#The where() function is used to replace values where the condition is False.
print(mySeries2.where(mySeries2 == 'Ajay','Akshay'))

Output
{1: 10, 2: 20, 3: 30}
1 10
2 20
3 30
dtype: int64
1 NaN
2 20.0
3 30.0
dtype: float64
1 10.0
2 NaN
3 NaN
dtype: float64
1 10.0
2 NaN
3 NaN
dtype: float64
1 10
2 33
3 33
dtype: int64
1 33
2 20
3 30
dtype: int64
1 Ajay
2 Dheeraj
3 Shanku
dtype: object
1 Ajay
2 NaN
3 NaN
dtype: object
1 NaN
2 Dheeraj
3 Shanku
dtype: object
1 Ajay
2 Akshay
3 Akshay
dtype: object
Program 8
Write a python program to create a DataFrame with custom column name/index

Program
import pandas as pd
myList = [['Ashima',12],['Mannat',14],['Samidha',15],['Jai',16]]
myDataFrame = pd.DataFrame(myList,columns=['Name','Roll No'])
print(myDataFrame)

Output
Name Roll No
0 Ashima 12
1 Mannat 14
2 Samidha 15
3 Jai 16
Program 9
Given a series s1 with some values in it. Write a program to sort the values in descending
order and store in s2 object, sort in ascending order and store in s3 object, store the squares
of the series in s3 object, store the squares of the series values in s4 object, display s4 object
values which are >7.

Program
import pandas as pd
s1=pd.Series([5,7,9,11,13,2,4,3])
s2=s1.sort_values(ascending=False)
s3=s1.sort_values
s4=s1**2
print(s1[s1>7])

Output
2 9
3 11
4 13
dtype: int64
Program 10
Write a python program that stores the sales of 5 items of a store for each month in 12 series
object that is s1 series object stores sales of these 5 items in 1st month, s2 stores of these
items in 2nd month and so on.

Program
import pandas as pd
s=pd.Series(['i1','i2','i3','i4','i5'])
s1=pd.Series([200,100,150,125,130])
s2=pd.Series([1200,1100,1150,1125,1130])
s3=pd.Series([400,400,450,425,430])
s4=pd.Series([500,400,650,325,530])
s5=pd.Series([400,400,350,325,430])
s6=pd.Series([300,300,350,325,330])
s7=pd.Series([s1+s2+s3+s4+s5+s6])
print(s7)

Output
0 0 3000
1 2700
2 3100
3 2650
4 2...
dtype: object
Program 11
Write a program to read details such as item sales made in a DataFrame and then store this
data in a csv file.

Program
import pandas as pd
c={'Fridge':[12],'Cooker':[5],'Juicer':[15],'Iron':[11]}
df= pd.DataFrame(c)
print(df)
df.to_csv('file.csv')

Output
Fridge Cooker Juicer Iron
0 12 5 15 11
Program 12
Write a program to consider the DataFrame created in Program 11 and display a menu to
show the following information regarding the DataFrame.
Transpose, Column names, indexes, datatypes of individual columns, size and shape of the
DataFrame.
Your program must keep on displaying as per the menu till the user’s choice.

Program
import pandas as pd
d1={'name':['rishi kumar','sehdev pal','simy ghosh','pooja tyagi','kapil arora'],
'city':['delhi','noida','delhi','gurgaon','gurgaon'],
'score':[560,800,1200,900,1060],
'qualify':['no','no','yes','yes','yes'],
'category':['gen','gen','st','sc','gen']
}
data=pd.DataFrame(d1, index=[12000,12001,12002,12003,12004])
print(data)
while(True):
print("MENU")
print("1. Display the Transpose")
print("2. Display all column names")
print("3. Display the indexes")
print("4. Display the shape")
print("5. Display the dimension")
print("6. Display the datatypes of all columns")
print("7. Display the size")
print("8. Exit")
n=int(input("Enter choice"))
if n==1:
print(data.T)
elif n==2:
print(data.columns)
elif n==3:
print(data.index)
elif n==4:
print(data.shape)
elif n==5:
print(data.ndim)
elif n==6:
print(data.dtypes)
elif n==7:
print(data.size)
elif n==8:
print("Good bye")
break
Output
name city score qualify category
12000 rishi kumar delhi 560 no gen
12001 sehdev pal noida 800 no gen
12002 simy ghosh delhi 1200 yes st
12003 pooja tyagi gurgaon 900 yes sc
12004 kapil arora gurgaon 1060 yes gen
MENU
1. Display the Transpose
2. Display all column names
3. Display the indexes
4. Display the shape
5. Display the dimension
6. Display the datatypes of all columns
7. Display the size
8. Exit
Enter choice1
12000 12001 12002 12003 12004
name rishi kumar sehdev pal simy ghosh pooja tyagi kapil arora
city delhi noida delhi gurgaon gurgaon
score 560 800 1200 900 1060
qualify no no yes yes yes
category gen gen st sc gen
Enter choice2
Index(['name', 'city', 'score', 'qualify', 'category'], dtype='object')
Enter choice3
Int64Index([12000, 12001, 12002, 12003, 12004], dtype='int64')
Enter choice4
(5, 5)
Enter choice5
2
Enter choice6
name object
city object
score int64
qualify object
category object
dtype: object
Enter choice7
25
Program 13
'''Bajaj Auto has given his sales figures of his North and East Region for the 1st quarter of the
financial year 2020. Present the same in the form of bar graph.

Sales(North Region) Sales ( East Region)


April 110 200
May 150 90
June 230 150
July 400 350
Write a program to represent the above given data as a DataFrame ( consider month as
indexes) and then print the graph. Put months as x axis and sales (of both region) as y axis.
Format the chart according to your wishes.

Program
import matplotlib.pyplot as plt
import pandas as pd
dict1={'north':[110,150,230,400], 'east':[200,90,150,350] }
df=pd.DataFrame(dict1, index=['April','May','june','July'])
print(df)
df.plot(kind='bar', color=['green','orange'])
plt.title("Comparison of Sales Month wise",fontsize=14,color="blue")
plt.xlabel("Month",fontsize=14,color="red")
plt.ylabel("Sales",fontsize=14,color="red")
plt.xticks(fontsize=10, rotation=30)
plt.show()

Output
Program 14
Considering the DataFrame created in Program 14 and present the sales of the east region
in the horizontal bar graph.

Program
import matplotlib.pyplot as plt
import pandas as pd
dict1={'north':[110,150,230,400], 'east':[200,90,150,350] }
df=pd.DataFrame(dict1, index=['April','May','june','July'])
print(df)
df['east'].plot(kind='barh', color=['green'])
plt.title("East Region Sales Month wise",fontsize=14,color="blue")
plt.xlabel("Sales",fontsize=14,color="red")
plt.ylabel("Month",fontsize=14,color="red")
plt.xticks(fontsize=10, rotation=30)
plt.show()

Output
Program 15
Write a program to convert csv into a data frame and then display it.

Program
import pandas as pd
df= pd.read_csv('MelaSales.csv')
print(df)

Output
Week 1 Week 2 Week 3 Day
0 5000 4000 4000 Monday
1 5900 3000 5800 Tuesday
2 6500 5000 3500 Wednesday
3 3500 5500 2500 Thursday
4 4000 3000 3000 Friday
5 5300 4300 5300 Saturday
6 7900 5900 6000 Sunday

You might also like