You are on page 1of 18

Program 1

Write a program to generate a series of numbers from 30 to 60 with an increment


of 5 each.

Solution:
import pandas as pd
import numpy as np
n=np.arange(30,60,5)
s=pd.Series(n)
print(s)
Output

Program 2
Write a program to generate a Series form an ndArray.

Solution:
import pandas as pd
import numpy as np
s=pd.Series(np.array([1,2,3,4,5]))
print(s)

Output
Program 3
Write a program to generate a series of 10 numbers with a scalar
value.
Solution:
import pandas as pd
s=pd.Series(50,range(1,11))
print(s)
Output

Program 4
Write a program to generate a series from a dictionary.
Solution:
import pandas as pd
d={'A':10,'B':20,'C':30}
s=pd.Series(d)
print(s)
Output
Program 5
Write python code to create a Series from the given list:
[890,450,235,789,256,572]
Answer the following Questions:
a) Find largest value
b) Display smallest value
c) Display the values that are more than 500
Solution:
import pandas as pd
li=[890,450,235,789,256,572]
s=pd.Series(li)
print(s)
print("Smallest value:\n",s.sort_values().head(1))
print("Largest value:\n",s.sort_values().tail(1))
print("Values more than 500")
print(s[s>500])
Output
Program 6
Create the following Data Frame Sales containing year wise sales figures
for five salespersons in INR. Use the years as column labels, and
salesperson names as row labels.

2020 2021 2022

Ankit 205 115 189

Ram 165 206 198

Nandini 190 179 169

a) Create the Data Frame.


b) Display the row labels of Sales.
c) Display the column labels of Sales.
d) Display the dimensions, shape, size and values of Sales.
Solution:
import pandas as pd
d={2020:[205,165,190],2021:[115,206,179],2022:[118,198,169]}
sales=pd.DataFrame(d,index=['Ankit','Ram','Nandini'])
print("Row Lables:\n",sales.index)
print("Column Lables:\n",sales.columns)
print("Dimensions:",sales.ndim)
print("Shape:",sales.shape)
print("Size:",sales.size)
print("Values:\n",sales.values)
Output
Practical 7
Write a program to create data frame from given table and answer the
question:
ID CITY CASES
101 DELHI 3000
110 MUMBAI 4000
120 SURAT 6000
a) To add a new row to store details or another city
b) To insert a row using iloc ()
c) To delete cases from dataframe
Solution:
import pandas as pd
Dict1={'ID':[100,110,120],'CITY':['DELHI','MUMBAI','SURAT'],'CASES':[3000,4000,6000]}
DF=pd.DataFrame(Dict1)
print("\nAfter adding a row using loc()")
DF.loc[3]=[140,'lucknow',7000]
print(DF)
print('\nAfter adding a row using iloc() ')
DF.iloc[3]=[150,'BENGLURU',8000]
print(DF)
print('\nAfter Delete column Cases')
DF.drop('CASES',axis=1,inplace=True)
print(DF)
Output
Practical 8
Using above Data Frame answer the following questions:
a) Write a code to add new column ‘Recovery’ using series method.
b) Write code to add column ‘death’.
c) Delete a new column ‘Recovery’.

Solution:
import pandas as pd
Dict1={'ID':[100,110,120],'CITY':['DELHI','MUMBAI','SURAT'],'CASES':[3000,4000,6000]}
df=pd.DataFrame(Dict1)
print("\nAdd a Column Recovery using Series()")
df['Recovery']=pd.Series([10,20,57],index=None)
print(df)
print("\nAdd a column Death")
df['Death']=[193,300,530]
print(df)
print("\nAfter Deleting Recovery Column")
print(df.drop('Recovery',axis=1))

Output:
Practical 9
Write a Program to Create a Data frame ‘Class’ From Two Series (Grade & Marks).
SOLUTION
import pandas as pd
ind=['VAISHNAVI','SHREYA','PRIYA']
grade=['A+','A','A']
marks=['99','98','95']
s1=pd.Series(grade,index=None)
s2=pd.Series(marks,index=None)
d={'Name':ind,'Grade':s1,'marks':s2}
Class=pd.DataFrame(d)
print(Class)
Output:
Practical 10
Create A Data frame Of Dictionary Consisting Of Name, Sub1, Sub2,
Sub3 Of 3 Students.
a) Display data frame
b) Display first 2 rows and last 3 rows
c) Add a new column ‘TOTAL’ contains the sum of all 3 subjects.
Solution:
import pandas as pd
df={"Name":['Kartikey','Sumit','Ayush'],
"Sub1":[85,52,56],
"Sub2":[52,56,54],
"Sub3":[89,87,85]}
student=pd.DataFrame(df)
print("Display DataFrame")
print(student)
print("\nDisplay first 2 rows\n",student.head(2),
"\nDisplay last 2 rows\n",student.tail(2))
print("\nDisplay the sum of all 3 subjects")
student['Total']=student['Sub1']+student['Sub3']+student['Sub3']
print(student)

Output:
PRACTICAL 11
Create a data frame using list and answer the following questions :-
[10,11,12,13],[23,34,45,32],[56,67,78,89]
a) Display data frame.
b) Add the list[1,2,3,4] to a data frame and display.
c) Delete 2nd row
SOLUTION:
import pandas as pd
L1= [10,11,12,13]
L2= [23,34,45,32]
L3= [56,67,78,89]
df=pd.DataFrame([L1,L2,L3])
print('display dataframe....')
print(df)
print('Adding a new list to data frame...')
df.loc[3]=[1,2,3,4]
print(df)
print('Deleting second row...')
print(df.drop(2,axis=0))

Output:
Practical 12
Create a data frame of [23, 25], [34], [43, 44, 45, 46] and answer the following questions:

a) Display data frame.


b) Replace missing value with 0.
c) Delete a column.

Solution:
import pandas as pd
L1= [23, 25]
L2= [34]
L3= [43, 44, 45, 46]
df= pd.DataFrame([L1,L2,L3])
print('Display Dataframe')
print(df)
print('\nReplace missing value with 0')
df.fillna('0',inplace=True)
print(df)
print('\n Delete a column')
df.drop(1,axis=1,inplace=True)
print(df)
Output:
Practical 13
Create a Data frame df that contains data about covid active cases in a society
block wise.
BLOCK TOTAL MEMBERS CASES
A 200 10
B 170 6
C 230 9
a) Write the command to display cases in ascending order.
b) Write the command to set the index to block.
c) Write the command to change the cases value from 6 to 12 in block ‘B’.
Solution:
import pandas as pd
d={'Block':['A','B','C'],'Total Members':[200,170,230],'Cases':[10,6,9]}
df=pd.DataFrame(d)
print("\nDisplay Cases in Ascending Order")
print(df.sort_values('Cases'))
print("\nSet index to BLOCK")
df.set_index('Block',inplace=True)
print(df)
print("\nChange the cases value from 6 to 12 in block ‘B’")
df.loc['B','Cases']=12
print(df)
Output
Practical 14
Create a Data frame df that contains data about students weight and height.
Answer the following Questions:
Name Weight Height
Tanya 50 163
Jiya 55 167
Shreya 59 164
a) Write the command to display records in descending order of Name.
b) Write the command to compute the sum of column Height.
c) Write the command to display the Maximum Weight.
Solution:
import pandas as pd
d={'Name':['Tanya','Jiya','Shreya'],'Weight':[50,55,59],'Height':[163,167,164]}
df=pd.DataFrame(d)
print(df)
print("\nDisplay Records in Descending Order of Name")
print(df.sort_values('Name',ascending=False))
print("\nDisplay the sum of Column Height")
print(df['Height'].sum())
print("\nDisplay Maximum Height")
print(df['Weight'].max())

Output
Practical 15
Write a program to find the total salary of all employees in the data
frame employee without using any aggregate function from the given
table.
Empno Ename Salary
E01 Ritu 12000
E02 Ankit 15000
E03 Megha 28000
Solution:
import pandas as pd
emp=['E01','E02','E03']
name=['Ritu','Ankit','Megha']
salary=[12000,15000,28000]
d={'Empno':emp,'Ename':name,'Salary':salary}
df=pd.DataFrame(d)
print(df)
sum=0
for i in range(len(df)):
sum=sum+df.loc[i,'Salary']
print("Sum of Salary=",sum)

Output
Practical 16
Write a program to plot the bar graph to display the total runs by
India in a match as below given the list:
Overs=[1-10,11-20,21-30,31-40,41-50]
Runs=[70,120,180,240,300]
Solution:
import matplotlib.pyplot as plt
overs=['1-10','11-20','21-30','31-40','41-50']
runs=[70,120,180,240,300]
plt.bar(overs,runs)
plt.title("Scored by India in 50 Overs")
plt.xlabel("Overs")
plt.ylabel("Runs")
plt.show()

Output
Practical 17
Write a program to plot the multiple bar chart for section-wise
students as below given the list:
Sections=[A, B, C, D]
S2019=[10,20,15,30]
S2020=[16,25,22,30]
S2021=[19,22,29,32]
Solution:
import matplotlib.pyplot as plt
import pandas as pd
Sections=['A','B','C','D']
S2019=[10,20,15,30]
S2020=[16,25,22,30]
S2021=[19,22,29,32]
df=pd.DataFrame({'2019':S2019,'2020':S2020,'2021':S2021},index=Sections)
df.plot(kind='bar', xlabel="Sections",ylabel="Strength")
plt.title("Students Strength Analysis")
plt.show()

Output
Practical 18
Write a program to plot the multiple line chart using data frame for
section-wise students as below given the list:
Sections=[A, B, C, D]
S2019=[10,20,15,30]
S2020=[16,25,22,30]
S2021=[19,22,29,32]
Solution:
import matplotlib.pyplot as plt
import pandas as pd
Sections=['A','B','C','D']
S2019=[10,20,15,30]
S2020=[16,25,22,30]
S2021=[19,22,29,32]
df=pd.DataFrame({'2019':S2019,'2020':S2020,'2021':S2021},index=Sections)
df.plot(kind='line',xlabel="Sections",ylabel="Strength",marker='o')
plt.title("Students Strength Analysis")
plt.show()

Output
Practical 19
Write a program to plot the multiple line chart without using data
frame for section-wise students as below given the list:
Sections=[A, B, C, D]
Students Strength=[10,20,15,30],[16,25,22,30],[19,22,29,32]
Solution:
import matplotlib.pyplot as plt
Sections=['A','B','C','D']
plt.plot(Sections,[10,20,15,30],marker='o',linestyle='dashed')
plt.plot(Sections,[16,25,22,30],marker='*',linestyle='dotted')
plt.plot(Sections,[19,22,29,32],marker='+',linestyle=’solid’)
plt.title("Students Strength Analysis")
plt.xlabel("Sections")
plt.ylabel("Strength")
plt.show()

Output
Practical 20
Write a program to plot the histogram using plot() with ‘Hist’
argument for section-wise students details as below given the list:
Name=[Anuj, Shruti, Rinku, Vinay]
Height=[60,63,68,70]
Weight=[48,40,52,58]
Solution:
import matplotlib.pyplot as plt
import pandas as pd
name=['Anuj','Shruti','Rinku','Vinay']
h=[60,63,68,70]
w=[48,40,52,58]
data={'Name':name,'Height':h,'Weight':w}
df=pd.DataFrame(data)
df.plot(kind='hist')
plt.show()

Output

You might also like