Python Pandas
Python Pandas
1. import pandas as pd
s1=pd.Series ([1, 2, 3, 4, 7, 2])
print (s1 [2])
Output
3
2. s1=pd.Series ([11, 12,13,14, 17] ,
index=[‘a’,’b’,’c’,’d’,’e’])
print (s1 [‘a’])
It will print the value corresponding to the labelled
index ‘a’.
o/p
11
import pandas as pa
list1= ["Ann","John","Denson","Lalu","Rahul"]
list2= [11, 22, 33, 44, 55]
s1=pa.Series (list1, index=list2)
print (s1 [11])
print (s1 [[22, 44]])
print (s1 [0:3])
print (s1 [1:3])
print(s1[-3:-1])
print(s1[[22,33]])
print(se.tail(3))
o/p
33 cinu
44 ram
55 rose
Mathematical Operations on Series
We can perform mathematical operations on two series
in Pandas.
While performing mathematical operations on series,
index matching is implemented.
A) Addition of two Series
Method 1
Eg. import pandas as pd
se1=pd.Series ([10, 20, 30, 40])
se2=pd.Series ([1,2,3,4])
print(se1+se2)
o/p0 11
1 22
2 33
3 44
To perform mathematical operations on 2 series, both
the series should have the same number of elements
and same index otherwise it will result in NaN(Not a
Number).
Method 2
import pandas as pd
se1=pd.Series ([10, 20, 30, 40], index= ['a','b','c','d'])
se2=pd.Series ([1, 2, 3, 4])
print (se1 * se2)
o/p
a NaN
b NaN
c NaN
d NaN
0 NaN
1 NaN
2 NaN
3 NaN
Method 2
se1=pd.Series ([10, 20, 30, 40], index= ['a','b','c','d'])
se2=pd.Series ([1, 2, 3, 4])
se1.mul(se2, fill_value=0)
(D) Division of two Series
Method 1
import pandas as pd
se1=pd.Series ([10, 20, 30, 40], index= ['a','b','c','d'])
se2=pd.Series ([1, 2, 3, 4])
print (se1 / se2)
o/p
a NaN
b NaN
c NaN
d NaN
0 NaN
1 NaN
2 NaN
3 NaN
Method 2
se1=pd.Series ([10, 20, 30, 40], index= ['a','b','c','d'])
se2=pd.Series ([1, 2, 3, 4])
se1.div(se2, fill_value=0)
Assignments
1. Create a series that stores the strength of 3 divisions
of XII std. as data and label each data with class
name. Print the series.
XII A 36
XII B 30
XII C 35
2. Create a series that stores the names of five of your
friends as data and their roll numbers as data labels
or indexes. Print the series.
3. Create a series that stores the names of class
teachers of std xii as data and their short forms as
labels. Print the name of the class teacher of xii b.
Xii a – Bindu - BV
Xii b – Abhilash - AGN
Xii c – Manju – MB
4. Create a series from a dictionary that stores the
basic colours as value and their code as key. (red
–‘R’,blue – ‘B’, green- ‘G’). Print the series.
5. Write the output of the following
import pandas as pd
se1=pd.Series([10,20,30,40])
print(se1*2)
print(se1.head(2))
print(se1.tail())
print(se1[3])
se1=se1*3
print(se1)
se1[2]=200
print(se1)
import pandas as pd
S1= pd.Series([23,65,78,89,11,21])
S1.sort_values()
O/p
4 11
5 21
0 23
1 65
2 78
3 89
To Sort the values in descending order use the following
syntax:
Seriesname.sort_values(ascending=False)
Example
S1.sort_values(ascending=False)
O/P
3 89
2 78
1 65
0 23
5 21
4 11
Assignment