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

Answers Practical File

The document contains code to perform operations on pandas DataFrames and Series. It includes examples of creating DataFrames from lists of data, selecting and filtering rows, adding and modifying columns, aggregating data using functions like sum and mean, sorting values, plotting graphs, and more. The code demonstrates many common tasks for working with tabular data in pandas.

Uploaded by

singhaladitya006
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)
9 views19 pages

Answers Practical File

The document contains code to perform operations on pandas DataFrames and Series. It includes examples of creating DataFrames from lists of data, selecting and filtering rows, adding and modifying columns, aggregating data using functions like sum and mean, sorting values, plotting graphs, and more. The code demonstrates many common tasks for working with tabular data in pandas.

Uploaded by

singhaladitya006
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/ 19

Answer 1:

import pandas

v = [99, 50, 75, 85, 55, 35, 40]


i = ['Raj', 'Ajay', 'Vijay', 'Gourav', 'Tina', 'Amay', 'Aakash']
Result = pandas.Series(v, index=i)
print(Result)
# ------------------------------------------
Result['Gourav'] = 87
print(Result[Result > 70])
print(Result[Result < 70].index)
print('Max = ', Result.max(), 'Min = ', Result.min(), 'Avg = ', Result.mean())
print(Result.head(4))
print(Result.tail())
Result = Result.drop('Aakash')
Result['Neeta'] = 95
print(Result.sort_values(ascending=False))
Result = Result-2
print(Result)

Output:

1|Page
Answer 2:
import pandas
eno = [1, 2, 1, 3, 2, 1, 3]
month = ['Jan', 'Jan', 'Feb', 'Jan', 'Feb', 'Feb', 'Feb']
salary = [90000, 80000, 95000, 50000, 82000, 95000, 60000]
d = {'Eno': eno, 'Month': month, 'Salary': salary}
EMP = pandas.DataFrame(d, index=['A', 'B', 'C', 'D', 'E', 'F', 'G'])
print(EMP)
print()
t = EMP[EMP['Eno'] == 1]
print('Sum = ', t.Salary.sum())

#OR

s=0
for ri, rd in EMP.iterrows():
if rd['Eno'] == 1:
s = s + rd['Salary']
print(‘Sum = ’, s)

Output:

2|Page
Answer 3:
import pandas

L = [[10, 'Raj', 50], [20, 'Ajay', 60], [30, 'Minu', 80], [40, 'Raj', 35], [50, 'Aakash', 90]]
df = pandas.DataFrame(L, index=['A', 'B', 'C', 'D', 'E'], columns=['Rno', 'Name', 'Marks'])
print(df)
print(df[df['Marks'] > 70])

Output:

Answer 4:
import pandas
L = [[10, 'Raj', 70], [20, 'Ajay', 69], [30, 'Vijay', 75], ['40', 'Tina', 99]]
df = pandas.DataFrame(L, columns=['Rno', 'Name', 'Marks'])
print(df)

Output:

3|Page
Answer 5:

import numpy as np
import pandas

rno = [10, 20, 30, 40, 50]


name = ['Raj', 'Ajay', 'Minu', 'Raj', 'Aakash']
marks = [88, 89, 55, 66, 77]
cls = ['XI', 'XII', 'XI', 'XII', 'XI']
d = {'Rno': rno, 'Name': name, 'Marks': marks, 'Class': cls}
df = pandas.DataFrame(d, index=['A', 'B', 'C', 'D', 'E'])
print(df)
print()
# ----------------------------------------------------------------------
print('Marks Of Minu = ', df.at['C', 'Marks'])
print('Marks Of Minu = ', df.iat[2, 2])
print(df.tail(3))
print(df.loc['A':'D', ['Rno', 'Marks', 'Class']])
print(df.loc[['A', 'C', 'E'], 'Name'])
print(df.loc[['A', 'E'], ['Rno', 'Class']])
df.at['B', 'Marks'] = 90
df['Grade'] = np.nan
df.loc['F'] = [60, 'Tina', 98, 'XII', np.nan]
df2 = df[['Rno', 'Name']]
df.Marks = df.Marks + 1
print(df)
print(df.iloc[1:4 , [1,3]])

4|Page
Output:

Answer 6:
import pandas
rno = [10, 20, 30, 40]
name = ['Raj', 'Ajay', 'Vijay', 'Gourav']
d = {'Rno': rno, 'Name': name}
df = pandas.DataFrame(d, index=['A', 'B', 'C', 'D'])
print(df)
df = df.sort_values('Name')
print(df)
Output:

5|Page
Answer 7:
import pandas
v = [10, 50, 5, 60, 90, 75]
i = ['Indore', 'Bhopal', 'Indore', 'Mumbai', 'Bhopal', 'Mumbai']
s = pandas.Series(v, index=i)
print(s)
print()
print(s['Indore'].sum())

Output:

Answer 8:
import pandas
rno = [10, 20, 30, 40, 50]
name = ['Raj', 'Ajay', 'Minu', 'Tina', 'Aakash']
points = [2, 1, -1, 1, -2]
d = {'Rno': rno, 'Name': name, 'Points': points}
df = pandas.DataFrame(d)
print(df)

for i in range(len(df)):
if df.iat[i, 2] < 0:
df.iat[i, 2] = 0

6|Page
#OR
for ri, rd in df.iterrows():
if df.at[ri, 'Points'] < 0:
df.at[ri, 'Points'] = 0
print(df)
Output:

Answer 9:
import pandas
rno = [10, 20, 30, 40, 50]
name = ['Raj', 'Ajay', 'Minu', 'Tina', 'Aakash']
marks = [88, 99, 90, 66, 70]
d = {'Rno': rno, 'Name': name, 'Marks': marks}
df = pandas.DataFrame(d)
print(df)
print()
print(df[(df['Marks'] >= 70) & (df['Marks'] < 95)])

7|Page
Output:

Answer 10:
import pandas
rno = [10, 20, 30, 40, 50]
name = ['Raj', 'Ajay', 'Minu', 'Tina', 'Aakash']
stream = ['Science', 'Commerce', 'Arts', 'Science', 'Arts']
marks = [88, 99, 55, 66, 77]
d = {'Rno': rno, 'Name': name, 'Stream': stream, 'Marks': marks}
df = pandas.DataFrame(d)
print(df)
df = df.drop(df[df['Stream'] == 'Arts'].index)
print(df)

Output:

8|Page
Answer 11:
import pandas
color = ['Red', 'Green', 'Red', 'Green', 'Green']
count = [3, 9, 25, 26, 99]
price = [120, 110, 125, 150, 70]
d = {'Color': color, 'Count': count, 'Price': price}
colors = pandas.DataFrame(d, index=['Apple', 'Apple', 'Pear', 'Pear', 'Lime'])
colors.loc['Coco'] = ['Red', 5, 90]
colors.Price = colors.Price + colors.Price * 10 / 100
colors['Amount'] = colors['Count'] * colors['Price']
print(colors)
print()
print(colors.head(3))
Output:

Answer 12:
import pandas
item = ['TV', 'TV', 'PC', 'AC']
comp = ['LG', 'VIDEOCON', 'LG', 'SONY']
rup = [12000, 10000, 15000, 14000]
usd = [700, 650, 800, 750]
d = {'Item': item, 'Company': comp, 'Rupees': rup, 'USD': usd}

9|Page
df = pandas.DataFrame(d)
print(df)
df.index = ['A', 'B', 'C', 'D']
# OR
df = df.rename({0: 'A', 1: 'B', 2: 'C', 3: 'D'})
print(df)
Output:

Answer 13:
import pandas
v = [10, 50, 5, 60, 90, 75]
i = ['Indore', 'Bhopal', 'Indore', 'Mumbai', 'Bhopal', 'Mumbai']
s = pandas.Series(v, index=i)
s = s.drop('Mumbai')
print(s)
Output:

Answer 14:
import pandas
rno = [10, 20, 30, 40, 50]
name = ['Raj', 'Ajay', 'Minu', 'Raj', 'Aakash']

10 | P a g e
sem1 = [50, 60, 80, 70, 90]
sem2 = [40, 50, 70, 50, 80]
d = {'Rno': rno, 'Name': name, 'SemI': sem1, 'SemII': sem2}
df = pandas.DataFrame(d)
print(df)
df['Total'] = df['SemI'] + df['SemII']
df['Percent'] = df['Total'] / 200 * 100
df['Grade'] = ['A' if x > 70 else 'B' for x in df['Percent']]
print(df)
#OR
for ri, rd in df.iterrows():
if rd[5] > 90:
df.at[ri, 'Grade'] = 'A'
else:
df.at[ri, 'Grade'] = 'B'
print(df)
Output:

11 | P a g e
Answer 15:
import numpy as np
import pandas
rno = [10, 20, 30, 40, 50]
name = ['Raj', 'Ajay', 'Vijay', 'Gourav', 'Tina']
marks = [50, 60, 85, 80, 90]
d = {'Rno': rno, 'Name': name, 'Marks': marks}
result = pandas.DataFrame(d)
print(result)
result.Marks = result.Marks + 5
result = result.drop(2)
result = result.drop('Marks', axis=1)
print(result)
result['City'] = np.nan
print(result)

Output:

12 | P a g e
Answer 16:
import pandas
import numpy as np
rno = [10, 20, 30, 40, 50]
name = ['Raj', 'Ajay', 'Minu', 'Tina', 'Aakash']
stream = ['Science', 'Commerce', 'Arts', 'Science', np.nan]
marks = [88, 99, np.nan, np.nan, 77]
d = {'Rno': rno, 'Name': name, 'Stream': stream, 'Marks': marks}
df = pandas.DataFrame(d)
print(df)
print(df.isnull().sum(axis=1))
print(df.isnull().sum(axis=0))
print(df.isnull().sum().sum())
df['Marks'] = df['Marks'].fillna(0)
print(df)
df = df.dropna()
print(df)
Output:

13 | P a g e
Answer 17:
import pandas
import matplotlib.pyplot as plt
df = pandas.DataFrame()
df['Rno'] = [10,20,30,40,50,60]
df['Name'] = ['Raj','Ajay','Vijay','Gourav','Tina','Vishesh']
df['Marks'] = [77,85,33,98,40,99]
print(df)
df.plot(kind='bar',x='Name',y='Marks',legend = False,color='red')
plt.title('Students Performance Chart')
plt.xlabel('NAMES')
plt.ylabel('MARKS')
plt.show()

Output:

14 | P a g e
Answer 18:
import pandas
import matplotlib.pyplot as plt
appdf = pandas.DataFrame()
appdf['Appname'] = ['Angry Birds', 'Teen Titans', 'PUBG Mobile', 'Marvel Comics', 'Fun
Run', 'WhatsApp', 'Temple Run', 'Google Duo']
appdf['Price'] = [100, 50, 200, 150, 25, 10, 170, 70]
appdf['Totaldownloads'] = [197, 210, 414, 196, 272, 668, 420, 110]
print(appdf)
appdf.plot(kind='bar', x='Appname', color=['blue','red'])
plt.xticks(rotation = 0)
plt.legend(['Price','Total downloads'], loc = 'upper right')
plt.title('Price and Downloads')
plt.xlabel('App Name')
plt.ylabel('Price and Downloads')
plt.show()

Output:

15 | P a g e
Answer 19:
import pandas
import matplotlib.pyplot as plt
Score = [8, 10, 15, 25, 28, 35, 47, 49, 50,
63, 67, 53, 57, 58, 69, 85, 83, 75,
95, 97, 87, 93, 98, 100]
s = pandas.Series(Score)

s.plot(kind='hist', bins=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
edgecolor = 'k', color='y')
plt.title('Marks Analysis')
plt.xlabel('Range')
plt.ylabel('No Of Students In The Range')
plt.legend(['Groupings'])
plt.show()

Output:

16 | P a g e
Answer 20:
import pandas
import matplotlib.pyplot as plt
name = ['Raj', 'Ajay', 'Vijay', 'Gourav', 'Tina']
sem1 = [95, 65, 65, 75, 87]
sem2 = [99, 75, 60, 79, 95]
df = pandas.DataFrame()
df['Name'] = name
df['Sem1'] = sem1
df['Sem2'] = sem2
print(df)
df.plot(kind='line', x='Name', linestyle='dotted',
linewidth=2,
color=['k', 'r'],
marker='D'
)
plt.title('RESULT')
plt.xlabel('NAMES OF STUDENTS')
plt.ylabel('MARKS')
plt.show()
Output:

17 | P a g e
Answer 21:

a. Select Cname, Amount


from PREPAID
where Model = 'Samsung' and Connection = 'Hutch'
order by Amount desc;

b. Select distinct Connection


from PREPAID;

c. Select Connection, sum(Validity)


from PREPAID
Group by Connection;

d. Select Connection, sum(Amount)


from PREPAID
Group by Connection
having Connection != 'Idea';

e. Select count(distinct model)


from Prepaid;

f. Select *
from PREPAID
where Cname like '_____';

(Five times underscore used)

g. Delete from PREPAID Where Cname = 'Karan';

h. Select Connection, count(distinct Model)


From PREPAID
Group By Connection;

i. Select Cname, ActivationDate


From PREPAID
Where monthname(ActivationDate) = 'January';

j. Select Connection, sum(Amount)


From PREPAID
Group by Connection
having sum(Amount) <= 3000;

18 | P a g e
Answer 22:
a. Select *
From club
Where sports = 'SWIMMING';

b. Select coachname, dateofapp


From club
Order by dateofapp desc;

c. Select coachname, pay, age, pay*15/100 as 'Bonus'


From club;
OR
Select coachname, pay, age, pay*15/100 'Bonus'
From club;

d. Select min(age)
From club
Where gender = 'F';

e. Select age, count(*)


From club
Group by age;

f. Select sports, sum(pay)


From club
Group by sports
Having count(*)>1;

g. Select *
From club
Where monthname(dateofapp) = 'March';

OR

Select *
From club
Where month(dateofapp) = 3;

h. Select coachname, dateofapp


From club
Where year(dateofapp) > 1996;

i. Select gender, min(pay), max(pay)


From club
Group by gender;

j. Update club
set pay = pay + pay*5/100 where gender = 'F';

19 | P a g e

You might also like