0% found this document useful (0 votes)
9 views34 pages

Ip Prac

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

Ip Prac

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

INFORMATICS PRACTICES

PRACTICAL FILE

PROGRAM 1
Q. Write a Program to create
i) Empty Series.
ii) To display the temperature of 7 days of a week using days as Index
iii) To display the temperature of 7 days of a week using numbers as Index.
Ans.
import pandas as pd
s=pd.Series()
s=pd.Series(index=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday',
'Sunday'],data=["17",15,19.6,18.5,15.2,19.3,20.0])
print(s)
PROGRAM 2
Q. Write a Program to create a Series of marks of 10 students and apply all
Series attributes to it. Add, subtract, multiply and divide the Series with
10.
Ans.
import pandas as pd
s=pd.Series(index=['Arya','Priya','Rohan','Crystal','Aditi','Shreya','Mahi','Kriti','Soham','Anisha'
], data=[56,98,67,54,66,87,34,99,25,58])
print(s)
print("The index of the series is",(s.index))
print("The values of the series is",(s.values))
print("The data type of the series is",(s.dtype))
print("The shape of the series is",(s.shape))
print("The number of bytes of the series is",(s.nbytes))
print("The size of the series is",(s.size))
print("To check whether the series is empty or not",(s.empty))
print("The dimension of the series is",(s.ndim))
s.name="Marks"
print("The name of the series is",(s.name))
s.index.name="Name"
print("The name of the index is",(s.index.name))
print(s.hasnans)
PROGRAM 3.
Q. Write a Program to create a Series of all month names and the number
of days in each month. Add 10 to each month, subtract 3 from each
month, multiply each month with 2 and lastly divide each month with 5.
Create another Series to display month names and number of working
days in each month and then calculate the number of holidays in each
month.
Ans.
import pandas as pd
s=pd.Series(data=[31,30,31,30,31,30,31,31,30,31,30,31],index=['January','February','March','A
pril','May','June','July','August','September','October','November','December'])
print(s)
print(s.index)
print(s.values)
print(s.dtype)
print(s.shape)
print(s.nbytes)
print(s.size)
print(s.empty)
print(s.ndim)
print(s.name)
print(s.index.name)
print(s.hasnans)
print(s+10)
print(s-3)
print(s*2)
print(s/5)
m=pd.Series(data=[23,19,24,24,25,0,28,25,29,24,26,25],index=['January','February','March','A
pril','May','June','July','August','September','October','November','December'])
print(m)
print('No. of holidays in each month',s-m)
PROGRAM 4

Q. Create 2 Series with different indexes and add them. After this
change the index of one Series.
Ans.
import pandas as pd
s=pd.Series(index=[1,2,3,4], data=[2,5,7,8])
r=pd.Series(data=[4,8,5,6])
print("Adding two series:","\n",s+r)
print(s)
print(r)
s.index=[0,1,2,3]
print(s)
PROGRAM5
Q. Write a Program to create a Dictionary which will have item names as
keys and Price as values. Convert the dictionary into a Series with name
‘Item’ and apply all attributes and functions to the Series.
Ans.
import pandas as pd
import pandas as pd
D={'Pen':20,'Pencil':7,'Eraser':20,'Paint':55,'Brush':20,'Washi Tape':60}
Item=pd.Series(D)
print(Item)
print(sum(Item))
print(max(Item))
print(min(Item))
print(Item.mean( ))
print(Item.mode( ))
print(Item.median())
print(Item.index)
print(Item.values)
print(Item.dtype)
print(Item.shape)
print(Item.nbytes)
print(Item.size)
print(Item.empty)
print(Item.ndim)
print(Item.name)
print(Item.index.name)
print(Item.hasnans)
PROGRAM 6
Q. Create a Series ‘Marks’. Write a command to display
i) Marks of last 2 students without using tail function
ii) Details of the given name
iii) Marks of alternate students
iv) Details of all those who got marks greater than 60
v) Details of first, third, and fourth student
Ans.
import pandas as pd
L1=eval(input("enter name:"))
L2=eval(input("enter marks:"))
s=pd.Series(data=L2,index=L1)
s.name="Marks"
print(s)
x=len(s)
print(s.iloc[(x-2):x])
y=input("enter name:")
print('marks:',s.loc[y])
print('alternate students:',s.iloc[0:x:2])
print("Students with marks above 60:",s[s>60])
print("Details of 1st, 3rd and 4th students:",s.iloc[0],s.iloc[2],s.iloc[3])
PROGRAM 7
Q. Write a Program to create a Series of 5 countries and their population
using list.
Display
i) Total population of all the countries
ii) Country with maximum population
iii) Country with minimum population
iv) Average population
v) Population of country given by user
Ans.
import pandas as pd
d={}
for i in range (0,5):
c=input("enter country")
p=int(input("enter population"))
d[c]=p
s=pd.Series(d)
print("Total population of all 5 countries", sum(s))
print("Country with max population", max(s))
print("Country with min population", min(s))
print("Avg. of population", s.mean())
c1=(input("enter chosen country"))
print("Population of country given by user", s.loc[c1])
PROGRAM 9
Q. Write a Program to create a Series of books in a library.
i) Try all the attributes
ii) Try all the functions
iii) Display the values of fiction and story books
iv) Display the values of indexes from 2nd to 5th
v) Display the details of all the books with quantity greater than 100
vi) Sort the books according to quantities
Ans.
import pandas as pd
L1=eval(input("enter genre:"))
L2=eval(input("enter qty.:"))
s=pd.Series(data=L2,index=L1)
print(s)
print(“All attributes:”)
print("Index:",s.index)
print("Values:",s.values)
print("Datatype:",s.dtype)
print("Dimension:",s.shape)
print("No. of Bytes:",s.nbytes)
print("No. of Elements:",s.size)
print("Is the series empty?",s.empty)
print("No.of Dimensions:",s.ndim)
s.name="Library"
s.index.name="Genre"
print("Are there null values?",s.hasnans)
print(s)
print(“All functions:”)
print("Top 5 values:",s.head())
print("Bottom 5 values:",s.tail())
print("Average:",s.mean())
print("Mode:",s.mode())
print("Median:",s.median())
print("Total:",sum(s))
print("Maximum value:",max(s))
print("Minimum value:",min(s))
print("values of Fiction & Fairy tales",s.loc['Fiction'],s.loc['FairyTales'])
print("Values from 2nd to 5th:", s.iloc[2:6])
print("Books with qty. >100:",s.loc[s>100])
print("Sorting according to qty.:",sorted(s,reverse=True))
PROGRAM 10
Q. Write a Program to create a Dataframe ‘Resources’, which has the
data regarding population, hospitals, and schools for 5 cities: Delhi,
Mumbai, Kolkata, Chennai, and Bangalore. Also apply all the attributes
and functions.
Ans.
import pandas as pd
d={"Population":[1500000,1200000,800000,800000,700000],"Hospital":[10000,8000,700
0,12000,7500],"School":[15000,15000,10000,9000,8000]}
df=pd.DataFrame(d,index=["Delhi","Mumbai","Kolkata","Chennai","Bangalore"])
df.name="Resources"
df.index.name="Cities"
print("Using Dictionary:","\n",df)
print("To show all attributes:-")
print("Index of the dataframe:","\
n",df.index) print("To display the values:","\
n",df.values) print("Dimensions:","\
n",df.shape) print("No. of elements:","\
n",df.size)
print("Is the dataframe empty:","\n",df.empty)
print("No. of dimension:","\n",df.ndim)
print("To check null values:","\n",df.isnull())
print(df.columns)
print(df.T)
print("To show all functions:-")
print("To display the top 5 values:","\n",df.head())
print("To display the bottom 5 values:","\n",df.tail())
print("To display the mean value:","\n",df.mean())
print("To display the middle value:","\n",df.median())
print("To display the most occuring value:","\n",df.mode())
print("To display the total:","\n",df.sum())
print("To display the max value:","\n",df.max())
print("To display the min value:","\n",df.min())
PROGRAM11
Q. Write a Program to create Series for an electronic shop where 5
electronic items have been displayed with their price.
i) Increase the price of laptop by 5%
ii) Decrease the price of T.V by 10%
iii) Display all the items whose price is greater than 63,000
iv) Display the price of first and fifth item
v) Multiply each item price by 5
Ans.
import pandas as pd
d={}
for i in range (0,5):
e=eval(input("enter electronic item:"))
p=eval(input("enter price:"))
d[e]=p
s=pd.Series(d)
print(s)
print("Increased price of laptop:",s.loc["laptop"]+s.loc["laptop"]*5/100)
print("Decreased price of television:",s.loc["television"]-s.loc["television"]*10/100)
print("Items with price greater than 63000:",s.loc[s>63000])
print("Price of first and fifth item:",s.iloc[0],s.iloc[4])
print("Price multiplied by 5",s*5)
PROGRAM 12
Q. Create a Dataframe using sublist.
Ans.
import pandas as pd d=[['aman',45],['vishal',56],
['soniya',67],['parth',78]]
df=pd.DataFrame(d,columns=['name','age'])
print(df)

PROGRAM 13

Q. Write a Program to create a Dataframe using dictionary and apply all


functions and attributes.
Ans.
import pandas as pd
dict1={'name':['aman','vishal','soniya','parth'],'marks':[45,56,67,78],'s_class':[12,12,12,12],'
sec':["A","A","E","D"]}
df=pd.DataFrame(dict1)
print(df)
df.name="Marklist"
print("Using Dictionary:","\n",df)
print("To show all attributes:-")
print("Index of the dataframe:","\
n",df.index) print("To display the values:","\
n",df.values) print("Dimensions:","\
n",df.shape) print("No. of elements:","\
n",df.size)
print("Is the dataframe empty:","\n",df.empty)
print("No. of dimension:","\n",df.ndim)
print("To check null values:","\n",df.isnull())
print("All columns:",'\n',df.columns)
print("Transposed view",'\n',df.T)
print("To show all functions:-")
print("To display the top 5 values:","\n",df.head())
print("To display the bottom 5 values:","\n",df.tail())
print("To display the mean value:","\n",df['marks'].mean())
print("To display the middle value:","\n",df['marks'].median())
print("To display the most occuring value:","\n",df['marks'].mode())
print("To display the total:","\n",df.sum())
print("To display the max value:","\n",df.max())
print("To display the min value:","\n",df.min())
PROGRAM14

Q. Create a Dataframe from a csv file.

Ans.
import pandas as pd
p=pd.read_csv("Prac14 (Projectcsv).csv")
project=pd.DataFrame(p)
print(project)
PROGRAM15
Q. Using the given Dataframe ‘Project’ display the class and project name
of each student.
i) Display all the names from given Dataframe
ii) Display the details of section-A only
iii) Display top 2 and bottom 3 records from given Dataframe
iv) Display the total no. of rows and columns in the Dataframe
v) Display the total elements in the Dataframe
vi) Change the view of Dataframe from vertical to horizontal

Ans.
import pandas as pd
p=pd.read_csv("Prac14 (Projectcsv).csv")
project=pd.DataFrame(p)
print(project)
print(project[["Name","Class","Project Name"]])
print(project[["Name"]])
print(project[project["Sec"]=='A'])
print("The top 2 records",project.head(2))
print("The bottom 3 values",project.tail(3))
print("Total no. of rows and columns",project.shape)
print("Total no. of elements",project.size)
print("Transposed view",project.T)
PROGRAM16
Q.Create a dataframe ‘Sales’
1. Create using all methods.
2. Add a column with a name difference, which will display the
difference of target and sales.
3. 3. Add another column bonus ,10% of sales amount
4. Increase the target of all zones by10%

import pandas as pd
sales1=pd.DataFrame([['Lee Know','TV',70000,39000],['Soobin','Laptop',23000,45000],['Han
Jisung','AC',120000,100000],['DPRian','Mobile',10000,8000]],
['ZoneA','ZoneB','ZoneC','ZoneD'],columns=['Name','Product','Target','Sales'])
print(sales1)
D={'Name':['Lee Know','Soobin','Han Jisung','DPRian'],'Product':
['TV','Laptop','AC','Mobile'],'Target':[70000,23000,120000,10000],'Sales':
[39000,45000,100000,8000]}
sales2=pd.DataFrame(D,index=['zoneA','zoneB','zoneC','zoneD'])
print(sales2)
sales2['Difference']=sales2['Target']-sales2['Sales']
print(sales2)
sales2['Bonus']=sales2['Sales']*0.10
print(sales2)
sales2["Target"]=sales2["Target"]+sales2["Target"]*0.10
print(sales2)
PROGRAM17
Q. Create a Dataframe from the given table using list, dictionary, and csv.

Ans.
import pandas as pd
import numpy as np
print("Using List")
L=[["R.K.Nath","ENT","M",12,300],
["Mahavir Singh","SKIN","M",np.NaN,500],
["M.Asthana","MEDICINE","F",9,250],
["V.S Nag","ENT","F",5,200],
["S.P Sinha","NEURO","M",20,500],
["J.P Pandey","CARDIOLOGY","M",1,400]]
Doctor=pd.DataFrame(L,index=[201,457,365,221,122,210],columns=["NAME","DEPT",
"GENDER","EXPERIENCE","CONSTFEES"])
print(Doctor)
print("Using Dictionary")
d={"NAME":["R.K.Nath","Mahavir Singh","M. Asthana","V.S. Nag","S.P. Sinha","J.P.
Pandey"], "DEPT":["ENT","SKIN","MEDICINE","ENT","NEURO","CARDIOLOGY"],
"GENDER":["M","M","F","F","M","M"],"EXPERIENCE":[12,np.NaN,9,5,20,1],"CONS
TFEES":[300,500,250,200,500,400]}
Doctor=pd.DataFrame(d,index=[201,457,365,221,122,210])
print(Doctor)
print("Using CSV")
p=pd.read_csv("Prac 17 (Doctorcsv).csv")
Doctor=pd.DataFrame(p)
print(Doctor)
PROGRAM18
Q. Write a code to create a Dataframe from the given table using
dictionary.
i) Write a command to add a new column ‘Selling Price’ which is the
result of unit price and discount.
ii) Increase the price of each item by 10%
iii) Add a new item with assumed details
iv) Change the details of the 3rd record
v) Add a new column at 2nd index value named as ‘Type’, which will
display the type of item.
vi) Delete the 3rd and 5th row.
vii) Delete the ‘Discount’ column at last.
viii) Display the total number of records by using Dataframe.

Ans.
import pandas as pd
import numpy as np
d={"Icode":['A21','B26','B35','C80','A30'],
'Item':["Frock","Cot",'Soft toy','Baby Socks','Pacifier'],
"DatePurchase":['2016-01-03','2015-09-23','2016-06-17','2014-10-16','2015-09-20'],
"UnitPrice":[700,5000,800,100,500],
"Discount":[10,25,10,7,5]}
df=pd.DataFrame(d)
print(df)
df["Selling Price"]=df["UnitPrice"]+df["Discount"]
print(df) df["UnitPrice"]=df["UnitPrice"]
+df["UnitPrice"]*10/100
df=df._append({'Icode':"B35",'Item':"Doll",'DatePurchase':"2007-07-
07",'UnitPrice':800,'Discount':20,'Selling Price':820},ignore_index=True)
print(df)
df.iloc[2]=['B20','Soft Teddy','2019-07-10',300,15,315]
print(df)
idx=2
df.insert(loc=idx,column='Type',value=['Cloth','Furniture','Toy','Cloth','Utility','Toy'])
print(df)
df=df.drop(df.index[[2,4]])
print(df)
del df['Discount']
print(df)
print("Total no. of records:",df.size)
PROGRAM 19
Q. Create a Dataframe from the given table using all the 3 methods: List,
Dictionary and csv.

Ans.
import pandas as pd
import numpy as np
print('Using Dictionary:')
d={'Names':['Sush','Adarsh','Ravi','Manu','Sushma'],'Phy':[34,np.NaN,56,67,np.NaN],'Che
m':[78,90,np.NaN,np.NaN,np.NaN],'Eng':[50,55,67,68,69],'Class':[9,10,10,11,11]}
df=pd.DataFrame(d,index=[100,101,102,103,104])
print(df)
print('Using List:')
L=[['Sush',34,78,50,9],['Adarsh',np.NaN,90,55,10],['Ravi',56,np.NaN,67,10],['Manu',67,np
.NaN,67,11],['Sushma',np.NaN,np.NaN,69,11]]
df1=pd.DataFrame(L,columns=["Name",'Phy','Chem',"Eng",'Class'],index=[100,101,102,1
03,104])
print(df1)
print('Using csv')
m=pd.read_csv("Prac 20 (Markscsv).csv")
df2=pd.DataFrame(m)
print(df2)

PROGRAM 20

Q. Create a Dataframe from the given table.


i) Write a command to insert a new row having the following
details: G, Sofa, East, 15.
ii) Write a command to add a new column ‘Price’ with some values.
iii) Replace the context of ‘Vname’ as Aamna, keeping the rest of the data
same for the item eraser.
iv) Write a command to delete the record with row label 203 permanently.
v) Write a command to delete the record with row label 202 and 205
permanently.
vi) Write a code to delete the column ‘Quantity’ using del, pop and drop.

Ans.
import pandas as pd d={"Vname":["A","B","C","E","F"],"Item":
['chair','table','pen','eeraser','sketch
pen'],'Area':['east','west','south','sw','ne'],'Qty':[30,45,23,12,100]}
df=pd.DataFrame(d,index=[200,201,202,203,204])
print(df)
df._append={'Vname':'G','Item':'Sofa','Area':'East','Qty':15}
print(df)
df.at[:,"Price"]=[2000,4000,8000,3000,10000]
df.loc[203,"Vname"]="Amna"
print(df)
df.drop(axis=0,labels=203,inplace=True)
print(df)
print("Deletion of column 'Qty:'")
print("1.Deletion using Del")
print("2.Deletion using Drop")
print("3.Deletion using Pop")
op=int(input("Choose method"))
if op==1:
del df['Qty']
elif op==2:
df.drop(axis=1,columns=['Qty'],inplace=True)
elif op==3:
df.pop('Qty')
else:
print("Option not available")
print(df)

You might also like