KR 7. Write Python code to create the Series EMP with the following data (using Dictionary):
Code
El Sanya
E2 Krish
E3 Rishav
£4 Deepak
Ans. import pandas as pd
d={"E1": "Sanya", "E2": "Krish", "E3";Rishav", "E4”:”Deepak”}
EMP=pd. Series (d)
EMP. index.name="Code"
print (EMP)@ Given a series that stores the area of some states in km?, write code to find out the largest and the smallest
three areas from the given series. The given series has been created like this:
Seri = pd. Series ([34567, 890, 450, 67892, 34677, 78902, 256711, 678291, 637632,
25723, 2367, 11789, 345, 256517])
‘Ans. import pandas as pd
Serl = pd. Series ([34567, 890, 450, 67892, 34677, 78902, 256711, 678291, 637632,
25723, 2367, 11789, 345,256517])
print ("Top 3 largest areas are:")
print (Serl.sort_values() .tail(3))
| print ("3 smallest areas are:")
print (Serl.sort_values() -head(3))
An alternative code for the above problem would be:
import pandas as pd
Serl = pd. Series ( (34567, 890, 450, 67892, 34677, 78902, 256711, 678291, 637632,
25723, 2367, 11789, 345, 256517])
print ("Top 3 largest areas are:")
print (Serl.sort_values (ascending = False) -head (3) )
print ("3 smallest areas are:")
print (Serl.sort_values (ascending=False) .tail(3))
Output:
Top 3 largest areas are:-
6 256711
8 637632
e 7 678291
" dtype: intea
3 smallest-areas are:
12 345
2 450
1 890
dtype: int64» Write @ program to find the total salary of all employees in the dataframe employee without using an)
aggregate function.
nk, import pandas as pd
G=({"Empno": [1,2,3],"Ename": ["Ritu", "Ankit", "Megha"], "Salary": [12000, 15000, 28000]}
df=pd.DataFrame (d)
print (df)
suml
for i in range (len (df)):
suml=suml+df.loc[i, 'Salary']
print (sum1)Write 2 Python program to create the given dataframe and sort the data in ascending order of age.
| wikstev [ao [cles |
\ti [35 [reer |ins. import pandas as pd
name=pd.Series(['Seema', 'Nikshav', 'Rajni'])
age=pd. Series ([36, 40, 39])
designation=pd. Series (['Manager', 'Clerk', 'Accountant'])
dl={'Name':name, 'Age':age, 'Designation':designation}
df=pd. DataFrame (d1)
print (df)
dfl=df.sort_values (by='Age')
—~ print (df£1)2 i ing dataset:
29. = the = = aa paprce Thane
Player eal 7 a
| Hardik Pandya _| Mumbai Indians satemen 8 4000
| KL Rahul Kings Eleven Batsmal ; am
Andre Russel Kolkata Knight Riders Batsman
i Indi Bowler | 10 200
Jasprit Bumrah _| Mumbai Indians an
Virat Kohli RCB Batsman 17 :
. [Rohit Sharma __| Mumbai indians Batsman | 15, 3700
(i) Create the dataframe IPL and retrieve the first two and last three rows using indexing.
Ans. Di={'Player': ['Hardik Pandya’, 'K L Rahul", "Andre Russel', 'Jasprit Bumrah!,
| 'Virat Kohli', 'Rohit Sharma'],
| ‘Team':['Mumbai Indians', 'Kings Eleven", 'Kolkata Knight Riders’, "Mumbai
i Indians', 'RCB', 'Mumbai Indians'],
| ‘Category':['Batsman', 'Batsman', 'Batsman', "Bowler', 'Batsman', 'Batsman'],
| ‘Bidprice':(13,12,7,10,17,15],
| 'Runs' : (1000, 2400, 900,200, 3600, 3700] }
IPL=pd.DataFrame (D1)
print (IPL)
print (IPL. iloc[:2,
print (IPL. iloc[-3;wie a Python code to create a dataframe with appropriate headings from the list given below:
C
‘s101', 'Amy', 70], ['S102', 'Bandhi', 69], ('S104', 'Cathy', 75],
['S105', 'Gundaho', 82]
Ans. import pandas as pd
#
data =
#
initialize list of lists
(['S101', 'Amy’,70],['S102', 'Bandhi',69],['S104', "Cathy',75],
['S105', 'Gundaho', 82] ]
Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Marks'})
#
print dataframe
print (df)38. Write a program that reads from a CSV file where the separator character is ‘S’, Read only the first 5 rows
| _ in Your dataframe. Give column headings as ItemName, Quantity, Price. Make sure to read the first row
| as data and not as column headers.
Ans
|
ndas as pd
a -read_csv("data.csv"
Sep="5",
names=("ItemName", "Quantity", "Price"]
header=None, nrows=5)
L> print (df)2. WAP to read details such as item and sales made in a dictionary and create a dataframe and then store this
dataframe in a CSV file.
: d= ('Fridge':[12], 'Cooker':(5], 'Juicer':[15], 'Iron':[11]}
Ans. import pandas as pd
d= {'Fridge':[12], 'Cooker':(5], 'Juicer': [15], 'Iron':[11]}
df = pd. DataFrame (d)
print (df)
_dE.to_csv("file.csv")43. WAP to read data from a CSV file ‘student’
where separator character is “@". Make sure that the old
columns should not appear as rows.
Ans. import pandas as pa
df = pd.read_csv('student.csv', sep='@', header=0)
print (df)Practical Implementation-36 S
Write a program to iterate over a dataframe containing names and marks, then calculate erat
as per marks (as per the following criteria) and add them to the grade column:
Marks >= 90 Grade A+
Marks 70 - 90 Grade A
Marks 60 - 70 Grade B
Marks 50 - 60 Grade C
Marks 40 - 50 Grade D
Marks < 40 Grade F
import pandas a: pd
import bumpy as np
names=pd. Series ({"sanjeev', "Rajeev", 'Sanjay', 'Abhay"))
narks=pd. Series ([76, 86, 55,54))
stud=("xane':nanes, ‘Marks' :marks)
fepd.Datafrane (stud, colums=[‘Name', ‘Marks'])
dE['Grace' J=np.tat fthis will add Naw toall records of datafrand
print ("Initial values in Datafreme")
print (df)
for (col,colseries) in ‘df.iteritems():
Jength=1en (colseries)
Af colmtmarks':
Asturks=[]
for row in range (length) :
mrks=colseries [row]
if mrks>=9}
Astérks.append('a+')
sora Initial values in DataFrame
eiitaressca Name Marks Grade
Astrks.append('2') 2 Sanjeev 76 NaN
elif mrks>=50: 2 Rajeev = 86 Nat
Asttrks.append('c') 2 sanjay 55 NaN
elif mrks>=40: 3 Abhay 540 Naw
Lstiirks.append(*D')
else:
istMrks.append('F') DataFrame after calculation of Grades
df['Grade')=1sturks Name Marks Grade
print ("\n\aDataFrane after calculation of Grades") {0 Sanjeev "fs Stade
[print (df) padeettace a
2 Sanjay 55 qj
3 Abhay sac