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

Practical

The document contains Python programming exercises involving data manipulation using Pandas, including generating student marks, creating dataframes for books and countries, and performing SQL queries on a charity and employee database. It includes tasks such as displaying specific data, plotting graphs, and writing SQL commands for data retrieval and manipulation. The exercises emphasize practical applications of data analysis and database management.
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)
2 views

Practical

The document contains Python programming exercises involving data manipulation using Pandas, including generating student marks, creating dataframes for books and countries, and performing SQL queries on a charity and employee database. It includes tasks such as displaying specific data, plotting graphs, and writing SQL commands for data retrieval and manipulation. The exercises emphasize practical applications of data analysis and database management.
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/ 6

1. Problem Solving using Python.

8
a. Write a program to generate a series of marks of 10 students. Give grace marks up to 3 marks of those who are having marks between 30 to 33 marks and print the
new list of the marks. (Pandas Series) [2]

ANS- import pandas as pd


std_marks = []
for i in range(1,11):
m = int(input("Enter the marks:"))
std_marks.append(m)
s = pd.Series(index=range(1201,1211),data=std_marks)
s[s==32]=s+1
s[s==31]=s+2
s[s==30]=s+3
print("New List is:")
print(s[s>=33])

b. Consider the following data for :

BookID Subject BookTitle Class Publisher Price

B0001 Computer Science NCERT Computer Science XII NCERT 270

B0002 Computer Science Move fast with computer science XII Dhanpat Rai 340

B0003 Computer Applications Sample Papers X BPB 120

B0004 Informatics Practices NCERT Computer Science XII NCERT 270

B0005 Artificial Intelligence Artificial Intelligence IX KIPS 340

B0006 Informatics Practices CBSE Questions Bank XII Oswal Books 299

import pandas as pd
import matplotlib.pyplot as mpp
#Answer 1
data={'BookID':['B0001','B0002','B0003','B0004','B0005','B0006'],\
'Subject':['Computer Science','Computer Science','Computer Appllications',\
'Informatics Practices','Artificial Intelligence','Informatics Practices'],\
'Class':['XII','XII','X','XII','IX','XII'],\
'Publisher':['NCERT','Dhanpat Rai','BPB','NCERT','KIPS','Oswal books'],\
'Price':[270,340,120,270,340,299]}
books=pd.DataFrame(data)
#Asnwer 2
print("Class XII Books:")
print(books[books['Class']=='XII'].to_string(header=False,index=False))
print("***********************************************************")
#Asnwer 3
print("Books having price more than 250")
print(books[books['Price']>250].to_string(header=False,index=False))
#Answer 4
books.plot(x='Subject',y='Price',kind='bar')
mpp.show()

1. Create a dataframe using lists. 1

Ans- data={'BookID':['B0001','B0002','B0003','B0004','B0005','B0006'],\
'Subject':['Computer Science','Computer Science','Computer Appllications',\
'Informatics Practices','Artificial Intelligence','Informatics Practices'],\
'Class':['XII','XII','X','XII','IX','XII'],\
'Publisher':['NCERT','Dhanpat Rai','BPB','NCERT','KIPS','Oswal books'],\
'Price':[270,340,120,270,340,299]}
books=pd.DataFrame(data)

2. Display books for class XII. 1

Ans- print("Class XII Books:")


print(books[books['Class']=='XII'].to_string(header=False,index=False))
print("***********************************************************")

3. Display the books whose price is more than 250. 1

Ans- print("Books having price more than 250")


print(books[books['Price']>250].to_string(header=False,index=False))

4. Plot these data on line chart. 3

Ans- books.plot(x='Subject',y='Price',kind='bar')
mpp.show()

2. SQL Queries 7

Consider the following table medicine and write answers for given questions below:
medicineID Medicinename Price Manufacturer

5147 Paracetamol 15 Dwarkesh Pharma

5274 D-Cold 20 Apollo Pharmacy

4296 Vicks VapoRub 45 Procter & Gamlbe

4175 Vicks Action 500 15 Procter & Gamble

4385 Soframycin 85 Sanofi

>>Create database company1; # database is being created

>> use company1; # we are entering into the database where we will work

>> create table medicine(medicineID int,Medicinename varchar(120),Price int, Manufacturer varchar(120)); #Table is created with the column name
and datatype

# Here we are going to insert the value into the table

>>insert into medicine values(5147,'Paracetamol',15,'Dwarkesh Pharma');

>> insert into medicine values(5247,'D-Cold',20,'Apollo Pharmacy');

>> insert into medicine values(4296,'Vicks VapoRub',45,'Procter & Gamble');

>> insert into medicine values(4175,'Vicks Action 500',15,'Procter & Gamble');

>> insert into medicine values(4385,'Soframycin',85,'Sanofi');

Observe the above medicine table and write queries for following:

a) Display the unique manufacturer from medicine.

Ans- select distinct(manufacturer) from medicine;

b) Display manufacturer and total price for each manufacturer

Ans- select manufacturer,sum(price) from medicine group by manufacturer;

c) Display manufacturer and price in the ascending order of price

Ans- select manufacturer,price from medicine order by price;

d) Display first 4 characters of medicinename which medicine id contains 5 as last digit

Ans- select left(medicinename,4) from medicine where medicineid like '%5';

e) Display all medicine names in Capital letter


Ans- select upper(medicinename) from medicine;

Write output of the following queries:


a) Select length(right(medicinename,4)) from medicine;

Ans.: length(right(medicinename,4))
————————————-
4
4
4
4
4
b) Select instr(price,5) from medicine;
Ans.: instr(price,5)
————————–
2
0
2
2
2

1. Problem Solving using Python. 8

Write a program in python to create the following dataframe named “country” storing the following details:

Country Population BirthRate UpdateDate

0 China 1379750000 12.00 2016-08-11

1 India 1330780000 21.76 2016-08-11

2 United States 324882000 13.21 2016-08-11

3 Indonesia 260581000 18.84 2016-01-07

4 Brazil 206918000 18.43 2016-08-11

5 Pakistan 194754000 27.62 2016-08-11

Considering the above dataframe answer the following question by writing appropriatecommand in python pandas:

import pandas as pd
import matplotlib.pyplot as plt
d={'country':['China','India','US','Indonasia','Brazil','Pakistan'],
'population':[1379750000,1330780000,324882000,260581000,206918000,194754000],
'birthrate':[12.00,21.76,13.21,18.84,18.43,27.62],
'updatedate':['2010-10-01','2010-01-04','2009-03-01','2009-04-01','2008-08-05','2010- 04-05']}
country=pd.DataFrame(d)

print("Answer 1")
print(country[country['country']=='China'].to_string(header=False,index=False))
print(country[country['country']=='India'].to_string(header=False,index=False))
print("Answer 2")
c=country.loc[:,['country','population','birthrate']]
print(c[c['country']=='Brazil'].to_string(header=False,index=False))
print(c[c['country']=='Pakistan'].to_string(header=False,index=False))

plt.bar(country['country'],country['population'],color=['r','g','b','c','m','y','k'])
plt.title("Population Report")
plt.xlabel("Country")
plt.ylabel("Population")
plt.grid()
plt.show()

country.to_csv('country.csv')

1. Display complete data for China and India.

Ans.- print("Answer 1")


print(country[country['country']=='China'].to_string(header=False,index=False))
print(country[country['country']=='India'].to_string(header=False,index=False))

2. Display Country, Population and BirthRate of Brazil and Pakistan.

Ans- print("Answer 2")


c=country.loc[:,['country','population','birthrate']]
print(c[c['country']=='Brazil'].to_string(header=False,index=False))
print(c[c['country']=='Pakistan'].to_string(header=False,index=False))
3. Create a CSV File from the above data frame.

Ans- country.to_csv('country.csv')

4. Now plot a bar chart depicting the Country on x-axis and their corresponding Population on y-axis, with appropriate Graph title, x-axis title, y-axis title, gridlines
an color etc.

Ans- plt.bar(country['country'],country['population'],color=['r','g','b','c','m','y','k'])
plt.title("Population Report")
plt.xlabel("Country")
plt.ylabel("Population")
plt.grid()
plt.show()

2. SQL Queries 7
Table – Charity

item_id Itemname Price Qty Pdate

1 Shoes 7500 5 2022/11/30

2 Socks 475 3 2022/08/25

3 Jeans 3500 5 2022/10/19

4 T-Shirts 1400 4 2022/11/30

>>create database charitywork; # Database is being created

>> use charitywork; # now we are entering into the database

>>create table charity(item_id int, Itemname char(50),Price int,Qty int,Pdate varchar(99)); # Table is created with the column name and
datatype

# Now we are goint to insert the values;

>>insert into Charity values(1,'Shoes',7500,5,'2022/11/30');

>> insert into Charity values(2,'Socks',475,3,‘2022/08/25’);

>> insert into Charity values(3,‘Jeans’,3500,5,‘2022/10/19’);

>> insert into Charity values(4,'T-Shirts',1400,4,'2022/11/30');

i) Display the name of week day when socks purchased.

Ans- select dayname(pdate) from charity;

ii) Display remainder after dividing price by qty

Ans- select mod(price,qty) from charity;

iii) Display the discount amount by 10% in two decimal places.

Ans- select round(price*0.10,2) from charity;

iv) Display the records of items purchased in the month 11.

Ans- select * from charity where month(pdate)=11

v) Display maximum qty purchased from the table.

Ans- select max(qty) from charity;

vi) Display itemname, price and qty in the descending order of price
Ans- select itemname, price, qty from charity order by price desc;

vii) Display item_id, itemname and position of s in each itemname.

Ans- select item_id,itemname, instr(itemname,'s') from charity;

1. Problem Solving using Python. 8


Write a program in python to create the following dataframe named “employee” storing
the following details:
EName Post Salary Dt_join

101 Anil Manager 65000 2018-03-02

102 Akshay Clerk 33000 2018-05-01

103 Ajay Manager 75000 2018-09-15

104 Varun Analyst 66000 2018-04-11

105 Siddharth Developer 60000 2018-10-12

106 Rajesh Clerk 35000 2018-06-12

import pandas as pd
import matplotlib.pyplot as plt
d={'Ename':['Anil','Akshay','Ajay','Varun','Siddharth','Rajesh'],
'Post':['Manager','Clerk','Manager','Analyst','Developer','Clerk'],
'Salary':[65000,33000,75000,66000,60000,35000],
'Dt_join':['2018-03-02','2018-05-01','2018-09-15','2018-04-11','2018-10-12','2018-06-12']}
employee=pd.DataFrame(d,index=[101,102,103,104,105,106])

print("Answer 1")
em=employee.loc[:,['Ename','Post','Salary']]
print(em[em.Salary>60000].to_string(header=False,index=False))
print("Answer 2")
employee.loc[employee.index[-1]+1]=['Ranveer','Analyst',65000,'2020-01-06']
print(employee.iloc[-1])
employee.to_csv('employees.csv')
plt.plot(employee['Ename'],employee['Salary'],color='r')
plt.title("Employee Analysis",color='blue')
plt.xlabel("Employee Names",color='red')
plt.ylabel("Salary",color='magenta')
plt.legend(['Salary'])
plt.show()

Considering the above dataframe answer the following queries by writing appropriate command in python pandas.
i. Display Name, Post and Salary for all employees earning more than 60000 .
Ans- print("Answer 1")
em=employee.loc[:,['Ename','Post','Salary']]
print(em[em.Salary>60000].to_string(header=False,index=False))

ii. Add a new row of your choice data.


Ans- print("Answer 2")
employee.loc[employee.index[-1]+1]=['Ranveer','Analyst',65000,'2020-01-06']
print(employee.iloc[-1])

iii. Transfer these data from dataframe to csv named employees.csv.


Ans. employee.to_csv('employees.csv')

iv. Now plot a multi-line chart depicting the Employee Name on x-axis and their corresponding Salary on y-axis, with appropriate Graph title, x-axis title, y-axis title, legends
and color etc.
Ans- plt.plot(employee['Ename'],employee['Salary'],color='r')
plt.title("Employee Analysis",color='blue')
plt.xlabel("Employee Names",color='red')
plt.ylabel("Salary",color='magenta')
plt.legend(['Salary'])
plt.show()
2. SQL Queries 7

Create the table “employee” and write sql queries for the following:

sl EName Post Salary Dt_join

101 Anil Manager 65000 2018-03-02

102 Akshay Clerk 33000 2018-05-01

103 Ajay Manager 75000 2018-09-15

104 Varun Analyst 66000 2018-04-11

105 Siddharth Developer 60000 2018-10-12

106 Rajesh Clerk 35000 2018-06-12

>>create database employee; # creating database


>> use employee; # entering into the database
>> create table employee(Sl int, FName char(20), Post char(25), Salary int,Dt_join DATE);
>> insert into employee values(101,'Anil','Manager',65000,'2015-03-02');
>> insert into employee values(102,'Akshay','Clerk',33000,'2018-05-01');
>> insert into employee values(103,'Ajay','Manager',75000,'2018-09-15');
>> insert into employee values(104,'Varun','Analyst',66000,'2018-04-11')
>> insert into employee values(105,'Siddharth','Developer',60000,'2018-10-12');
>> insert into employee values(106,'Rajesh','Clerk',35000,'2018-06-12');

Write queries for the following:


a) Count and display employees post wise.
Ans- select post,count(*) from employee group by post;

b) Display 3 characters from 2nd place from the column ename.


Ans- select mid(ename,2,3) from employee;

c) Display last 2 characters of post column.


Ans- select right(post,2) from employee;

d) Display ename in lower letters


Ans- select lower(ename) from employee;

e) Display most senior employee


Ans- select min(Dt_join) from employee;

Write output of the following:


a) Select max(dt_join) from employee;
Ans.: max(dt_join)
———————-
2018-10-12

g) Select instr(ename,’a’) from employee


Ans- instr(ename,a)
—————-
1
1
1
2
6
2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy