0% found this document useful (0 votes)
31 views

Pandas-Series &DF-Term1-24-25

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Pandas-Series &DF-Term1-24-25

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Ex.No.

1 SERIES DATA STRUCTURE CREATION


1) Write a python code to create empty series data structure.
Coding: import pandas as pd
a=pd.Series()
print(a)
Output: Series([], dtype: float64)
2) Write a python program to create a series object, country using a list that stores the capital of
each country.
Note: Assume four countries to be used as index of the series object are India, UK, Denmark,
and Thailand having capitals as New Delhi, London, Copenhagen, and Bangkok respectively.
Coding: import pandas as pd
l=['India','UK','Denmark','Thailand']
i=['New Delhi','London','Copenhagen','Bangkok']
country=pd.Series(l,index=i)
print(country)
Output:

3) Write a python code to create the following series object by using dictionary method.

Coding: import pandas as pd


di={'Corbett':'Uttarakhand','Sariska':'Rajasthan','Kanha':'Madya Pradesh','Gir':'Gujarat'}
NP=pd.Series(di)
print(NP)
Output:

4) Write a python code to create series data structure by using dictionary method.
Coding: import pandas as pd
d={1:'One',2:'Two',3:'Three'}
s=pd.Series(d)
print(s)
Output:

5) Write a python code to create series data structure by using scalar value method.
Coding: import pandas as pd
b=pd.Series('Yet to start',index=[5,10,15])
print(b)
Output:

6) Write a python code to create series data structure by using mathematical functions.
Coding: import numpy as np
import pandas as pd
b=np.arange(5)
d=pd.Series(b*2,index=['a','b','c','d','e'])
print(d)
Output: a 0
b 2
c 4
d 6
e 8
dtype: int32
Ex. No.2 OPERATIONS ON SERIES DATA STRUCTURE
1) Write a python program to create a series data structure which stores the monthly salary of 10
employees. Write a command to perform the following operations on it.
i. Display the first 3 employee’s salaries.
ii. Display the last 5 employee’s salaries.
iii. Display the annual income of employees.
iv. Display the names of employees who are getting salary more than 7000.
v. Display the salary of employees increased by 200.

Coding: import pandas as pd


names=['Rahul','Arvind','Keshav','Bharathi','Anjali','Shankar','Priya','Mohammed','Anas','Karth
i']
salary=[6750,2900,8000,7050,5000,3500,9000,6050,6000,8100]
s=pd.Series(salary,index=names)
print(s)
print("__________________")
print("DISPLAYING FIRST 3 EMPLOYEES SALARIES")
print(s.head(3))
print("_____________________")
print("DISPLAYING LAST 5 EMPLOYEES SALARIES")
print(s.tail())
print("________________")
print("DISPLAYING ANNUAL INCOME OF ALL EMPLOYEES")
print(s*12)
print("_________________")
print("DISPLAYING THE NAMES OF EMPLOYEES WHO ARE GETTING SALARY
MORE THAN 7000")
print(s[s>7000])
print("__________________")
print("DISPLAY THE SALARY INCREASED BY 200")
print(s+200)
print("_________________")
Output:
2) Write a command to perform the following operations on the series data structure ‘s’. (By
using slicing, loc and iloc methods)
i. List the salaries of Arvind to Shankar.
ii. List the employee’s salaries in reverse order.
iii. List the last 7 names using loc method.
iv. List the first 5 rows by using iloc method.
v. Print Anjali’s salary.
vi. Change the Anas’s salary by 6500 and print the series.
Coding: print("_________________")
print("SALARY OF ARVIND TO SHANKAR")
print(s[1:6])
print("_________________")
print("NAMES IN REVERSE ORDER")
print(s[::-1])
print("_________________")
print("LAST 7 NAMES")
print(s.loc['Bharathi':])
print("________________")
print("FIRST 5 ROWS")
print(s.iloc[:5])
print("________________")
print("PRINT ANJALI'S SALARY")
print(s['Anjali'])
print("________________")
print("CHANGE ANAS'S SALARY TO 6500")
s['Anas']=6500
print(s)
Output:
Ex. No.3 DATAFRAME DATA STRUCTURE CREATION
1) Write a python code to create a dataframe with headings (a and b) from the list given below:

Coding: import pandas as pd


d1={‘a’:1,’b’:2}
d2={‘a’:3,’b’:4}
d3={‘a’:5,’b’:6}
d4={‘a’:7,’b’:8}
l=[d1,d2,d3,d4]
a=pd.DataFrame(l)
print(a)
Output: OUTPUT:

2) Write a python code to print the following data frame by using dictionary of series.
Coding: import pandas as pd
names=pd.Series(['Malar','Arun','Mahi'])
classes=pd.Series(['XII','XI','XII'])
mark1=pd.Series([78,80,90])
mark2=pd.Series([96,98,90])
mark3=pd.Series([90,89,90])
dict={'Name':names,'Class':classes,'English':mark1,'Economics':mark2,'Accountancy':mark3}
stu_df=pd.DataFrame(dict)
print(stu_df)
Output:

Ex. No.4) DATAFRAME-OPERATIONS ON DATAFRAME


1) Answer the questions based on the dataframe given. Consider the name of the dataframe is df.

a) Write a python pandas code to create above dataframe named df.


b) Add a new column Quarter5 with following values 1000,2000,3000,4000,5000
c) Add a new row with a value the default value 10000.
d) To delete a column named ‘Quarter4’.
e) Delete the rows with index numbers 1 and 4.
Coding: import pandas as pd
dict={'Quarter1':[2000,4000,5000,4400,10000],'Quarter2':[5800,2500,5400,3000,2900],'Quart
er3':[20000,16000,7000,3600,8200],'Quarter4':[1400,3700,1700,2000,6000]}
df=pd.DataFrame(dict)
print("DATA FRAME")
print("--------------------------")
print(df)
print("---------------------------")
print("ADDING A NEW COLUMN QUARTER5")
print("----------------------------")
df['Quarter5']=[1000,2000,3000,4000,5000]
print(df)
print("---------------------------")
print("ADDING A NEW ROW")
print("---------------------------")
df.loc[5]=10000
print(df)
print("---------------------------")
print("DELETING COLUMN QUARTER4")
print("---------------------------")
del df['Quarter4']
print(df)
print("---------------------------")
print("DELETING ROWS")
print("---------------------------")
print(df.drop([1,4],axis=0))
print("---------------------------")
Output:
2) Consider the given Data frame ‘health’.
Diseasename Agent
0 Common cold Virus
1 Chickenpox Virus
2 Cholera Bacteria
3 Tuberculosis Bacteria
Write suitable python statements for the following.
i. Remove the row containing details of disease named ‘Tuberculosis’.
ii. Add a new disease named ‘Malaria’ caused by ‘Protozoa’.
iii. Display the last two rows.
Coding: import pandas as pd
d1={0:'Common cold',1:'Chickenpox',2:'Cholera',3:'Tuberculosis'}
d2={0:'Virus',1:'Virus',2:'Bacteria',3:'Bacteria'}
di={'Diseasename':d1,'Agent':d2}
health=pd.DataFrame(di)
print(health)
print("________________________")
print("REMOVE TUBERCULOSIS")
health=health.drop(3)
print(health)
print("________________________")
print("ADD A NEW DISEASE MALARIA")
health.loc[4]=['Malaria','Protozoa']
print(health)
print("_________________________")
print("DISPLAY LAST TWO ROWS")
print(health[2:])
Output: Output:
Diseasename Agent
0 Common cold Virus
1 Chickenpox Virus
2 Cholera Bacteria
3 Tuberculosis Bacteria
________________________
REMOVE TUBERCULOSIS
Diseasename Agent
0 Common cold Virus
1 Chickenpox Virus
2 Cholera Bacteria
________________________
ADD A NEW DISEASE MALARIA
Diseasename Agent
0 Common cold Virus
1 Chickenpox Virus
2 Cholera Bacteria
4 Malaria Protozoa
_________________________
DISPLAY LAST TWO ROWS
Diseasename Agent
2 Cholera Bacteria
4 Malaria Protozoa
3) Consider the given DataFrame ‘Genre’:

Write suitable Python statements for the following:


i. Add a column called Num_Copies with the following data: [300,290,450,760].
ii. Add a new genre of type ‘Folk Tale' having code as “FT” and 600 number of copies.
iii. Rename the column ‘Code’ to ‘Book_Code’.
Coding: import pandas as pd
s1=pd.Series(['Fiction','Non Fiction','Drama','Poetry'])
s2=pd.Series(['F','NF','D','P'])
d={'Type':s1,'Code':s2}
Genre=pd.DataFrame(d)
print(Genre)
print("Adding a new column Num_Copies")
Genre['Num_Copies']=[300,290,450,760]
print(Genre)
print("_____________________")
print("Adding a new Row")
Genre.loc[4]=['Folk Tale','FT',600]
print(Genre)
print("_____________________")
print("Renaming the column Code to Book_Code")
Genre=Genre.rename({'Code':'Book_Code'},axis=1)
print(Genre)
print('_____________________')
Output:
4) Given a data frame df1 as shown below. Answer the following questions:

a) Write a command to list the weather details of Bengaluru and Kolkata.


b) Write a command to list the weather details of Delhi, Bengaluru and Chennai.
c) Write a command to list Mumbai’s MaxTemp and Rainfall.
d) Write a command to list MinTemp and Rainfall of all cities.
e) Write a command to display the column MaxTemp.
f) Write a command to list the Maximum and minimum temperature of Chennai.
g) Write command to list of RainFall of Delhi to Chennai
h) Write command to list of MaxTemp and MinTemp of Bengaluru to Mumbai by using iloc.
Coding: import pandas as pd
dict={'MaxTemp':[40,31,35,29,39],'MinTemp':[32,25,27,21,23],'RainFall':[24.1,36.2,40.8,35.2
,41.8]}
weather=pd.DataFrame(dict,index=['Delhi','Bengaluru','Chennai','Mumbai','Kolkata'])
print(weather)
print("-----------------------------------")
print("DETAILS OF BENGALURU AND KOLKATA")
print("-------------------------------")
print(weather.loc[['Bengaluru','Kolkata']])
print("---------------------------------")
print("DETAILS OF DELHI, BENGALURU AND CHENNAI")
print("---------------------------------")
print(weather[:3])
print("------------------------------------")
print("MUMBAI'S MAXTEMP AND RAINFALL")
print("-----------------------------------")
print(weather.loc['Mumbai',['MaxTemp','RainFall']])
print("------------------------------------")
print("MINTEMP AND RAINFALL OF ALL CITIES")
print("----------------------------------")
print(weather[['MinTemp','RainFall']])
print("----------------------------------")
print("MAXTEMP OF ALL CITIES")
print("----------------------------------")
print(weather['MaxTemp'])
print("----------------------------------")
print("MAXTEMP AND MINTEMP OF CHENNAI")
print("----------------------------------")
print(weather.loc['Chennai','MaxTemp':'MinTemp'])
print("----------------------------------")
print("RAINFALL OF DELHI TO CHENNAI USING ILOC")
print("----------------------------------")
print(weather.iloc[0:3,2])
print("-----------------------------------")
print("MAXTEMP AND MINTEMP OF BENGALURU TO MUMBAI USING ILOC")
print("-----------------------------------")
print(weather.iloc[1:4,:2])
print("-----------------------------------")
Output:
Ex.No.5) IMPORTING AND EXPORTING DATA BETWEEN CSV AND DATAFRAMES

1) Write a python code to convert a CSV file ‘test1.csv’ into a dataframe.


Contents of CSV file as

Coding: import pandas as pd


a=pd.read_csv("test1.csv")
print(a)
Output:

2) Write a python code to convert dataframe into a CSV file with a name t.csv.
import pandas as pd
a.to_csv(r"t.csv",index=False,header=True)

You might also like