Yashas RajuIP Practical File
Yashas RajuIP Practical File
import pandas as pd
s1=pd.Series([15,39,45,77,62,93,88])
print(s1)
s2=p.Series((37,54,27,18,13,93,48,79),index=[4,5,6,7,8,9,10,11])
print(s2)
3. Write a program to create a series object using a string 'python programming' and index is
'IP'. Assume that pandas is imported as alias name pd.
import pandas as pd
s4=pd.Series(['python programming','information'],index=['ip','info'])
print(s4)
1
5. Write a program to create a series with 2 different lists. series object as 'series', data
[31,28,31,30,31,30] , index['jan','feb','march','april','may','june'].
import pandas
data=[31,28,31,30,31,30]
index=['jan','feb','march','april','may','june']
series=pandas.Series(data,index=index)
print(series)
s=pandas.Series(range(5),index=range(1,6))
print(s)
2
7. Write a program to create a series object from n dimensional array.
import pandas as pd
import numpy as np
ndarr=np.arange(3,15,4)
print(ndarr)
s7=pd.Series(ndarr)
print(s7)
8. Write a program
import pandas as pd
import numpy as np
ndarr2=np.arange(1,101,5)
print(ndarr2)
s8=pd.Series(ndarr2)
print(s8)
3
9. Write a program to create a series object using a ndarray that has 5 elements in the range
of 25 to 65.
import pandas as pd
import numpy as np
ndar3=np.linspace(25,65,5)
print(ndar3)
s9=pd.Series(ndar3)
print(s9)
10. Write a program to create a series object using tile function list[2,20] thrice.
import pandas as pd
import numpy as np
s10=pd.Series (np.tile([2,20],3))
print(s10)
4
11. Write a program to create a series object s1 and s2 by using the arange function (10,15)
as index for s1 and s2 and s1 data is index values *2 and for s2 index value**2
import pandas as pd
import numpy as np
x=np.arange(10,15)
s1=pd.Series(index=x,data=x*2)
s2=pd.Series(x**2,x)
print(s1)
print(s2)
import pandas as pd
s12=pd.Series([23.9,87.5,93.7,88.8,79.2,63.4,28.2,19.7],index=[1,5,9,3,2,8,7,4])
print(s12[0:9:2])
5
print(type(s12))
s2=s12[::2]
print(s2)
print(type(s2))
import numpy as np
s13=pd.Series([14.5,29.3,18.75,46.0,83.2],index=[2,4,6,8,10])
s13.index=['a','c','e','g','i']
print(s13)
14.Write a program
import pandas as pd
6
import numpy as np
s2=pd.Series([125,233,918,733],index=[4,5,6,7])
s2.index=[8,9,10,11]
s2[8]=345
s2[1:3]=893
s2[11]=473
print(s2)
15.Write a program
import pandas as pd
import numpy as np
nd=np.arange(30,40,2)
s2=pd.Series(nd)
print(s2)
print("adding 5 to s2")
print(s2+5)
print("adding 18 to s2")
print(s2+18)
7
16. Write a program to perform various arithmetic operations on various series object
import pandas as pd
import numpy as np
s1=pd.Series([1,2,3,4])
8
s2=pd.Series([5,6,7,8])
print(s1+s2)
print(s2-s1)
print(s1*s2)
print(s2/s1)
17. Write a program to display the details of the students opted for various electives
import pandas as pd
import numpy as np
cls11=pd.Series([15,25,35],index=["Math","IP","Entreu"])
cls12=pd.Series([18,24,15],index=["Math","IP","Entreu"])
9
18. Write a program to display the details of charity contributions of various sections of
class10.
and check if contributions are more than 500'''
import pandas as pd
import numpy as np
cls10=pd.Series([555.50,489.55,493.50,703.55],index=['A','B','C','D'])
print(cls10[cls10>500])
print(cls10>500)
19. Write a program to display the details of the students opted for various electives
import pandas as pd
import numpy as np
cls11=pd.Series([15,25,35],index=["Math","IP","Entreu"])
cls12=pd.Series([18,24,15],index=["Math","bst","Entreu"])
print("adding students of same electives")
print(cls11+cls12)
10
20. Write a program to check the greater
import pandas as pd
import numpy as np
s1=pd.Series([1,2,3,4])
s2=pd.Series([5,6,7,8])
print("s1 greater than 3")
print(s1[s1>3])
21. Write a program to display the details of charity contributions of various sections of
class10 and check if contributions are more than 500.
import pandas as pd
import numpy as np
cls10=pd.Series([555.50,489.55,493.50,703.55],index=['A','B','C','D'])
print(cls10[cls10>500])
print(cls10>500)
11
22. Write a program to create a series object s1 and display the sorted values in ascending
and descending.
import pandas as pd
import numpy as np
s1=pd.Series([49,54,73,18,124,19,82])
print(s1.sort_values())
print(s1.sort_values(ascending=False))
12
23. Write a program to create a series object s1 having index[5,9,4,3,2,10,15] and display the
sorted values in ascending and descending.
import pandas as pd
import numpy as np
s1=pd.Series([94,89,43,27,154,38,12],index=[5,9,4,3,2,10,15])
print(s1.sort_index())
print(s1.sort_index(ascending=False))
print(s1.sort_index(ascending=True))
13
import pandas as pd
import numpy as np
class10=pd.Series([250,375,497,827,900],index=['english','math','accountancy','business','IP'])
class11=pd.Series([333,475,893,725,800],index=['english','math','accountancy','business','IP'])
class12=pd.Series([545,873,944,812,783],index=['english','math','accountancy','business','IP'])
print("Total no. of children appearing for all exams from class 10,11 and 12")
print(class10+class11+class12)
print("Total no. of children appearing for english exam from class 10 and 12")
print(class10["english"]+class12["english"])
print("No. of class 11 IP students")
print(class11["IP"])
print(" No. of children appearing for Accountany,IP and English exams from class 11")
print(class11[::2])
print("Adding 10 students to all subjects of class 12")
print(class12+10)
14
Series Attributes
import pandas as pd
a=pd.Series(data=[1,2,3,4,5])
print(a.nbytes)
print(a.dtype)
print(a.shape)
print(a.size)
print(a.index)
print(a.hasnans)
print(a.ndim)
a.name="my series"
print(a)
print(a.empty)
print(a.values)
15
26. Data type
import numpy as np
import pandas as pd
y=pd.Series(data=[13.7,18.9,122.4,57.3,],index=[43,87,92,44])
print(y.dtype)
import pandas as pd
x=pd.Series(data=[2,4,6,8,],index=['red','blue','yellow','green'])
x.index.name='colours'
print(x.index.name)
28.Nbytes
import pandas as pd
a=pd.Series(data=[1,2,3,4,5])
b=pd.Series(data=[4.9,8.2,5.6],index=['x','y','z'])
print(a.nbytes,b.nbytes )
29. Shape
import numpy as np
import pandas as pd
16
x=pd.Series(data=[2,4,6,8,],index=['red','blue','yellow','green'])
print(x.shape)
30. Values
import numpy as np
import pandas as pd
x=pd.Series(data=[2,4,6,8,],index=['red','blue','yellow','green'])
print(x.values)
17
DataFrame
1. import pandas as pd
import numpy as np
d1={'students':['harika','tanmaya','raju','kashish','nikitha','purvi'],'Hobbies':['painting','baking','
gaming','crochet','dancing','sleeping']}
df1=pd.DataFrame(d1)
print(df1)
2. import pandas as pd
d2={'fruits':['apple','banana','mango'],'colour':['red','blue','green']}
d2=pd.DataFrame(d2,index=[1,2,3])
print(d2)
import pandas as pd
import numpy as np
NA1=np.array([[1,2],[3,4,5,6],[7,8,9,10]])
df1=pd.DataFrame(NA1)
print(df1)
18
5. import pandas as pd
s1=pd.Series([25,50,75])
s2=pd.Series([18000,29000,57000])
s3=s1*2
d1={'A':s3,'B':s2}
df1=pd.DataFrame(d1)
print(df1)
6. import pandas as pd
import numpy as np
#2d dictionary of dict
d1={'Population':{'Mumbai':23400,'Bangalore':34500,'Delhi':54343},
'Hospitals':{'Mumbai':765,'Bangalore':553,'Delhi':545},
'School':{'Mumbai':7655,'Bangalore':7457,'Delhi':5434}}
df=pd.DataFrame(d1)
print(df)
df1=pd.DataFrame(d2,index=['Mumbai','Blr','delhi'])
print(df1)
19
7. Create a Data Frame for Accessing data using loc & iloc (Indexing using Labels).
import pandas as pd
cols = ['Red','Green','Blue','Yellow','Orange']
cont = [15,17,21,25,19]
price = [95,105,113,120,109]
datas={'Colors':cols,'Count':cont,'Price':price}
df1 = pd.DataFrame(datas,index=['Apple','Grapes','Blueberry','Mango','Orange'])
print(df1)
print(df1.loc['Apple',:])
print(df1.loc[['Blueberry'],['Colors','Price']])
print(df1.loc['Grapes':'Mango',['Count']])
print(df1.iloc[0:3])
print(df1.iloc[[1,3]])
print(df1.iloc[2:3,0:1])
20
8. Create a Data Frame
import pandas as pd
d={'ItemCategory':['Mobile', 'Laptop', 'DSLR Camera', 'Earbuds', 'Smart Watch', 'DSLR Camera',
'Mobile', 'Laptop', 'Mobile'],
'ItemName':['Google Pixel', 'HP', 'Cannon', 'Sony', 'Apple', 'Nikon', 'iPhone', 'Dell', 'OnePlus'],
'Expenditure':[60000,120000,63000,17000,14000,71000,69000,85000,38000]}
df=pd.DataFrame(d)
21
print(df)
DataFrame Attributes
9. import pandas as pd
data={'marketing':[25,'neha','female'],'sales':[24,'rohit','male']}
df1=pd.DataFrame(data,index=['age','name','gender'])
print(df1.index)
print(df1.columns)
print(df1.axes)
print(df1.dtypes)
print(df1.size)
print(df1.shape)
22
Data Visualisation
1. import numpy as np
passpercentage1=[90,92,94,95,97]
passpercentage2=[89,91,93,95,98]
plt.bar(year,passpercentage1,color='g',label='r1')
plt.bar(year,passpercentage2,color='b',label='r2')
plt.legend()
plt.xlabel("Year")
plt.ylabel("Pass percentage")
plt.title("Pass percentage till 2018")
plt.show()
23
2. import numpy as np
per=[94,85,45,25,50,54]
index=np.arange(len(label))
plt.bar(index,per)
plt.show()
3. import pandas as pd
import matplotlib.pyplot as plt
males=[150,200,250,300,350,400,450]
females=[50,100,150,200,250,300,350]
day=[1,2,3,4,5,6,7]
plt.plot(day,males,color='b',label='male',linewidth=5,marker='*',markersize=10,markeredgecol
or='white')
24
plt.plot(day,females,color='m',label='female',linewidth=5,marker='h',markersize=10,markered
gecolor='white')
plt.xlabel("Days")
plt.ylabel("Sales")
plt.savefig("bar3")
plt.show()
4. Write a Python Program to plot Line Chart for Salary Hike of an Employee.
import matplotlib.pyplot as pl
Year = [2000,2004,2005,2006,2008,2010,2012,2014,2015,2016,2018,2020]
Salary= [9000,15000,17000,20000,22000,25000,28000,31000,35000,39000,45000,50000]
pl.plot(Year,Salary,label= 'Salary',)
pl.xlabel ('Years')
pl.ylabel ('Salary')
25
pl.show()
5. Write a Python Program to plot the Pass Percentage of the Year 2019 & 2020, Classes 6th
to 12th using Line Chart.
import matplotlib.pyplot as pl
Class2019=[6,7,8,9,10,11,12]
PP2019=[98,98,98,90,98,86,98]
PP2020=[100,100,100,96,100,92,100]
pl.plot(Class2020, PP2020, label= 'Year 2020')
26
6. Write a Python Program to display a Histogram Graph for Blood Sugar Values based on No.
of Patients.
import matplotlib.pyplot as pl
BloodSugar=[105,96,80,145,147,88,93,150,125,86,77,93,127]
pl.ylabel("No.Of.Patients")
pl.hist(BloodSugar,bins=[75,100,125,150])
pl.legend(['Men'],title="Histogram",loc='upper right')
pl.show()
7. Given the school result data, analyses the performance of the students on different
parameters, e.g. subject wise or class wise.
27
import matplotlib.pyplot as pl
Subject=['Maths','Phy.','Chem.','Bio.','C.Sc.','English','Tamil','Hindi']
Percentage=[86,84,78,86,94,87,90,88]
pl.bar(Subject,Percentage,align='center')
pl.xlabel('Subject', fontsize=18)
pl.show()
8. For the Data Frames created above, analyse and plot appropriate charts with title and
legend.
Source Code:
import matplotlib.pyplot as pl
import numpy as np
Subject=['Maths','Sci.','Social']
UT1_Percentage=[56,54,40,]
UT2_Percentage=[62,60,42]
UT3_Percentage=[50,60,40]
l=np.arange(len(Subject))
28
pl.bar(l,UT1_Percentage,width=.25,label='UT1')
pl.bar(l+.25,UT2_Percentage,width=.25,label='UT2')
pl.bar(l+.50,UT3_Percentage,width=.25,label='UT3')
pl.xticks(l,Subject)
pl.legend(title="TestNames",loc='best')
pl.show()
a=['BLR','DEL','CHN','KOL']
b=[150000,190000,175000,135000]
plt.xlabel("CITY")
plt.ylabel("POPULATION")
plt.title("CITY - POPULATION")
plt.show()
29
10. How to specify different widths for different bars of bar chart?
a=['BLR','DEL','CHN','KOL']
b=[150000,190000,175000,135000]
plt.xlabel("CITY")
plt.ylabel("POPULATION")
plt.title("CITY - POPULATION")
plt.show()
30
11. How to change the colours of the Bars in a Bar Chart?
a=['BLR','DEL','CHN','KOL']
b=[150000,200000,185000,135000]
plt.xlabel("CITY")
plt.ylabel("POPULATION")
plt.title("CITY - POPULATION")
plt.show()
medal =['Gold','Silver','Bronze','Total']
India=[26,20,20,66]
Canada=[15,47,10,62]
plt.bar(medal,India,color='g',label='India')
plt.bar(medal,Canada,color='r',label='Canada')
plt.xlabel("Medals Scored")
plt.ylabel("Country")
plt.legend(loc="upper left")
31
plt.show()
Names=('Asma','Bela','Chris','Diya','Saqib')
#Create horizontal bars
plt.barh(Names,height)
plt.xlabel("Height")
plt.ylabel("Names")
plt.show()
32
14. How to change line style?
a=['BLR','DEL','CHN','KOL']
b=[150000,200000,185000,135000]
plt.ylabel("CITY")
plt.xlabel("POPULATION")
plt.title("CITY - POPULATION")
plt.show()
33
15. How to create a histogram?
plt.show()
16. Take Data of your interest from an open source (e.g. data.gov.in), aggregate and
summarize it. Then plot it using different plotting functions of the Matplotlib Library.
import pandas as pd
import matplotlib.pyplot as pl
34
cf=pd.read_csv("D:\MostRuns.csv")
print(cf,'\n')
s=(cf['Team'].head(12))
s2=(cf['Runs'].head(12))
pl.bar(s,s2)
pl.legend(‘Runs’, loc=’best’)
pl.show()
35
CSV
1. Write a program to print data from csv file “CSV example.csv”
import pandas
df=pandas.read_csv("CSV example.csv")
print(df)
2. Code to print data from csv file “Marks.csv” and create columns total and average
import pandas
df1=pandas.read_csv("Marks.csv")
print(df1)
df1['Total']=df1['English']+df1['Maths']+df1['Science']
df1['Average']=df1['Total']/3
print(df1)
36