Data Frame and Series
Data Frame and Series
SERIES
UNIT 5(PANDAS LIBRARY)
INTRODUCTION TO SERIES
Create series :
Import pandas as pd
S= pd.Series([1,2,3])
Print(S)
OUTPUT:
0 1
1 2
2 3
CREATE A SIMPLE PANDAS SERIES FROM A
LIST:
Example code:
• import pandas as pd
• a = [1, 7, 2]
• myvar = pd.Series(a)
• print(myvar)
Labels:
• If nothing else is specified, the values are labeled with their index number. First
value has index 0, second value has index 1 etc.
• This label can be used to access a specified value.
• print(myvar[0]) #return first element of the series
CREATE LABELS
• import pandas as pd
• a = [1, 7, 2]
• myvar = pd.Series(a, index = ["x", "y", "z"])
• print(myvar)
CREATE A SIMPLE PANDAS SERIES FROM A
DICTIONARY:
• import pandas as pd
myvar = pd.Series(calories)
print(myvar)
print(myvar)
CREATE A SERIES FROM SCALAR
• import pandas as pd
• s = pd.Series([1,2,3,4,5])
• #retrieve the first three element
• print s[:3]
• Example 3-Retrieve the last three elements.
• import pandas as pd
• s = pd.Series([1,2,3,4,5])
• #retrieve the last three element
• print s[-3:]
RETRIEVE DATA USING LABEL (INDEX)
CONVERT PANDA SERIES TO LIST
• import pandas as pd
• ds = pd.Series([2, 4, 6, 8, 10])
• print("Pandas Series and type")
• print(ds)
• print(type(ds))
• print("Convert Pandas Series to Python list")
• print(ds.tolist())
• print(type(ds.tolist()))
CONVERT A GIVEN SERIES TO AN ARRAY.
• import pandas as pd
print("Multiply two Series:")
• ds1 = pd.Series([2, 4, 6, 8, 10]) mul= ds1 * ds2
• ds2 = pd.Series([1, 3, 5, 7, 9]) print(mul)
print("Divide Series1 by Series2:")
• add = ds1 + ds2 div = ds1 / ds2
• print("Add two Series:") print(div)
• print(add)
• print("Subtract two Series:")
• sub = ds1 - ds2
• print(sub)
INTRODUCTION TO DATA FRAME
INTRODUCTION TO DATA FRAME
• import pandas as pd
• stu_data = [(1,'Akshit',19,'male','jammu'),
• (2,'Samer',20,'male','Syria'),
• (3,'Harsh',20,'male','UP'),
• (4,'Nirmaljeet kaur',28,'female','Hoshiarpur'),
• (5,'jeremiah',18,'male','zambia')]
• df =
pd.DataFrame(stu_data,columns=['reg_id','Name','Age','Gender','City'])
• df