0% found this document useful (0 votes)
13 views12 pages

IP grade 12 record

The document contains a series of Python programming tasks focused on creating and manipulating pandas Series and DataFrames, performing mathematical operations, visualizing data with Matplotlib, and interacting with SQL databases. Each task includes code snippets demonstrating how to achieve specific objectives, such as filtering data, joining DataFrames, and generating plots. Additionally, it outlines SQL commands for database management and querying employee data.

Uploaded by

bhimireddypragna
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)
13 views12 pages

IP grade 12 record

The document contains a series of Python programming tasks focused on creating and manipulating pandas Series and DataFrames, performing mathematical operations, visualizing data with Matplotlib, and interacting with SQL databases. Each task includes code snippets demonstrating how to achieve specific objectives, such as filtering data, joining DataFrames, and generating plots. Additionally, it outlines SQL commands for database management and querying employee data.

Uploaded by

bhimireddypragna
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/ 12

1. Write a python program to create a series using a dictionary.

import pandas as pd
dict1={“Rahul”:85,”Arjun”:90,”Ankitha”:95}
s1=pd.Series(dict1)
print(s1)

2. Write a python program to create a series using python sequence.

import pandas as pd
s1=pd.Series([11,22,33,44,55])
print(“series object1:”)
print(s1)

3. Write a python program to create a series using scalar value.

import pandas as pd
s1=pd.Series(5000,index=[‘q1’,’q2’,’q3’,’q4’])
print(s1)

4. Write a python program to create a series using ndarray

import pandas as pd
import numpy as np
nda1=np.arange(3,13,3.5)
print(nda1)
s1=pd.Series(nda1)
print(s1)
s2=pd.Series(np.linspace(20,50,4))
print(s2)
s3=pd.Series(np.tile([5,6],3))
print(s3)

5. Write a series program to print all the elements that are above the
th
75 percentile.

import pandas as pd
import numpy as np
s=pd.Series(np.array([1,2,3,4,5,6,7,8,9,10]))
print(s)
ans=s.quantile(q=0.75)
print()
print('75th percentile of series=')
print(ans)
print()
print(s[s>ans])

6. Write a python program for performing mathematical operations using


series object.

import pandas as pd
s1=pd.Series(data=[9,8,7,6,5])
s2=pd.Series(data=[2,3,4,5])
print("sum")
print(s1+s2)
print("difference")
print(s1-s2)
print("product")
print(s1*s2)
print("division")
print(s1/s2)

7. Write a python program that uses series object attributes.

import numpy as np
import pandas as pd
x=pd.Series(data=[2,4,6,8])
y=pd.Series(data=[11,22,33,44,np.NaN],index=['a','b','c','d','e'])
print(x.index)
print(x.values)
print(y.index)
print(y.values)
print(x.shape)
print(y.shape)
print(x.ndim)
print(y.ndim)
print(x.size)
print(y.size)
print(x.hasnans)
print(y.hasnans)

8. Write a Pandas program to join the two given dataframes along rows
and assign all data.

import pandas as pd
stdata1=pd.DataFrame({'stid':['S1','S2','S3','S4','S5'],
'name':['Deepthi','Rohit','Sanvi','Tarun','Kavya'],
'marks':[200, 210, 190, 222, 199]})
stdata2=pd.DataFrame({'stid':['S4','S5','S6','S7','S8'],
'name':['Arnav','Chaitanya','Gargi','Sathvik','Manvi'],
'marks':[201, 200, 198, 219, 201]})
print("Source DataFrames:")
print(stdata1)
print("----------------------------")
print(stdata2)
print("\ntwo dataframes after joining along rows:")
result=pd.concat([stdata1,stdata2])
print(result)

9. Write a Pandas program to append a list of dictionaries or series to a


existing DataFrame and
display the combined data.

import pandas as pd
stdata1 = pd.DataFrame({
'stid': ['S1','S2','S3','S4','S5'],
'name': ['Harini','Riyan','Bhanu','Akash','Sarayu'],
'marks': [200, 210, 190, 222, 199]})
s6=pd.Series(['S6','Kevin', 205],index=['stid','name','marks'])
dicts= [{'stid': 'S6', 'name': 'Kevin', 'marks': 203},
{'stid': 'S7', 'name': 'Bhanu', 'marks': 207}]
print("Main DataFrames:")
print(stdata1)
print("\nDictionary:")
print(s6)
joineddata=stdata1._append(dicts,ignore_index=True,sort=False)
print("\njoinedData:")
print(joineddata)

10. To write a Python program to create a pandas DataFrame to analyze


The students marks in respective subjects. Also, perform the
following operations.
(i) To Change the name of Grade10 to Tenth.
(ii) To Count and Display Non-NaN values of each column.
(iii) To Count and Display Non-NaN values of each row.
(iv) To Increase the marks any subject by 1.
(v) To Replace all NaN values with 0.

import pandas as pd
import numpy as np
s1=pd.Series([80,90,100,100],index=['eng','sci','maths','IT'])
s2=pd.Series([99,np.NaN,98,90],index=['eng','sci','maths','IT'])
s3=pd.Series([np.NaN,90,99,96],index=['eng','sci','maths','IT'])
s4=pd.Series([99,89,100,99],index=['eng','sci','maths','IT'])
s5=pd.Series([98,96,np.NaN,100],index=['eng','sci','maths','IT'])
df=pd.DataFrame({'grade10':s1,'grade9':s2,'grade11':s3,'grade4':s4,'
grade10A':s5})
print("source dataframe")
print(df)
print("change the name from grade10 to Tenth")
df.rename(columns={'grade10':"tenth"},inplace=True)
print(df)
print("counting and displaying the non-NaN values in columns")
print(df.count())
print("counting and displaying the non-NaN values in rows")
print(df.count(1))
print("Increasing the marks in english by adding one mark")
df.loc['eng',:]=df.loc['eng',:]+1
print(df)
print("change all the NaN values with zero")
df.fillna(0,inplace=True)
print(df)

11. Create a python program to filter the data of a dataframe.

Ename Department Salary


E012 Heera Sales 20000
E015 Aadhya Accounts 25000
E021 Bharath Sales 22000
E026 Naren HR 30000
E051 Chatur Accounts 25000

import pandas as pd
emp={'Ename':['Heera','Aadhya','Bharath','Naren','Chatur'],
'Department':['Sales','Accounts','Sales','HR','Accounts'],
'Salary':[20000,25000,22000,30000,25000]}
df=pd.DataFrame(emp,index=['E012','E015','E021','E026','E051'])
print(df.loc[df['Salary']>24000])

12. Write a python program which uses descriptive statistics with pandas.

import pandas as pd
import numpy as np
dict1={'fruits':[7830.0,11950.0,113.0,7152.0,44.1,140169.2],
'pulses':[931.0,818.0,1.7,33.0,23.2,2184.4],
'rice':[7452.4,1930.0,2604.8,11586.2,814.6,13754.0],
'wheat':[np.NaN,2737.0,np.NaN,16440.5,0.5,30056.0]}
df1=pd.DataFrame(dict1,index=['Andhra','Gujarat','kerala','Punjab','
Tripura','UttarP'])
print(df1)
print(df1.mode())
print(df1.mean())
print(df1.median())
print(df1.quantile([.25,.5,.75,1]))
print(df1.describe())
print(df1.info())
print(df1.head())
print(df1.tail())

13. Write a python program to perform writing and reading operations in


a CSV file.

import pandas as pd
emp={'Ename':['Heera','Aadhya','Naren','Chatur'],
'Department':['Sales','Accounts','Sales','HR'],
'area':['lane1','lane2','lane3','lane4'],
'Salary':[20000,25000,22000,30000]}
df=pd.DataFrame(emp,index=['E012','E015','E021','E026'])
df.to_csv("C:\\Users\\Lenovo\\Desktop\\emp.csv")
data=pd.read_csv("C:\\Users\\Lenovo\\Desktop\\emp.csv")
print(data)

14. Write a python program to show the connectivity between MySQL and
Python Dataframe.

import pandas as pd
import mysql.connector as sqltor
mycon=sqltor.connect(host="localhost",user="root",passwd='1234',
database='vahila1')
if mycon.is_connected():
df1=pd.read_sql("select * from student;",mycon)
print(df1)
else:
print("connection problem")

15. Write a python program to display the data of a data frame row wise
and column wise using iterrows() and items().

import pandas as pd
d={'sname':['Krithi','Arjun','Chaitanya','Naithik','Geethu'],
'qualification':['MCA','MBA','Bsc','B.tech','M.E'],
'percentage':[95,96,80,85,99]}
df=pd.DataFrame(d,index=['st1','st2','st3','st4','st5'])
for (row,values) in df.iterrows():
print(row)
print(values)
print()
for (col,values) in df.items():
print(col)
print(values)
print()

16. Write a python program to plot a line chart based on the given data.
Also, give appropriate axes labels, title and keep marker style as
diamond and marker edge color as ‘red’ for product1.

import matplotlib.pyplot as plt


weeks=[1,2,3,4]
prod1=[65,45,30,80]
prod2=[18,30,40,35]
plt.title("price report")
plt.xlabel("weeks")
plt.ylabel("prices")
plt.plot(weeks,prod1,marker='D',markersize=10,markeredgecolor='r')
plt.plot(weeks,prod2)
plt.show()

17. To write a Python program to create a DataFrame for subject-wise


average, save it to a CSV file, and then draw a bar chart using
Matplotlib with a width of each bar as 0.50, specifying different colors
for each bar. Additionally, provide a proper title and axes labels for the
bar chart.

import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame({'subject':['eng','phy','maths','chem','IP'],
'sub-avg':[72,85,78,92,80]},
index=['sub1','sub2','sub3','sub4','sub5'])
df.to_csv("C:\\Users\\Lenovo\\Desktop\\new.csv")
data=pd.read_csv("C:\\Users\\Lenovo\\Desktop\\new.csv")
plt.title("subject analysis report")
plt.xlabel("subjects")
plt.ylabel("average")
plt.bar(data['subject'],data['sub-avg'],
width=0.50,color=['c','r','g','b','m'])
plt.show()

18. To write a Python program to plot a multiple bar chart From CSV file
using Matplotlib for subject wise Scores of Class A, Class B, and
Class C. Different colors represent each class, and subjects include
English, Accountancy, Economics, BST and IP. Proper labels,
a title and a legend are displayed on the chart.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data={'subject':['eng','acc','eco','bst','IP'],
'classA':[85,78,92,80,98],
'classB':[90,65,88,75,87],
'classC':[75,82,60,90,94]}
df=pd.DataFrame(data)
df.to_csv("C:\\Users\\Lenovo\\Desktop\\new1.csv")
new=pd.read_csv("C:\\Users\\Lenovo\\Desktop\\new1.csv")
plt.xlabel('subjects')
plt.ylabel('average')
plt.title("subjectwise analysis for classes A, B, C")
x=np.arange(5)
plt.bar(df['subject'],df['classA'],width=0.25,label='class--A')
plt.bar(x+0.15,df['classB'],width=0.25,label='class--B')
plt.bar(x+0.30,df['classC'],width=0.25,label='class--C')
plt.legend()
plt.show()

NOTE: All SQL commands to be written on right


side single ruled page of record and outputs on left
white page.
(write question first and in same single ruled paper put the
heading as SQL commands and write SQL commands as
answers.
All questions at top of page followed by answers)

1. Implement the following SQL commands:


CREATE, SHOW, USE, INSERT, DESC

empno ename job mgr hiredate sal comm deptno


8369 Smith Clerk 8902 1990-12-18 800 null 20
8499 Anya Salesman 8698 1991-02-20 1600 300 30
8521 Seth Salesman 8698 1991-02-22 1250 500 30
8566 Mahadevan Manager 8839 1991-04-02 2985 null 20
8654 Momin Salesman 8698 1991-09-28 1250 1400 30
8698 Bina Manager 8839 1991-05-01 2850 null 30
8882 Shivansh Manger 8839 1991-06-09 2450 null 10
8888 Scott Analyst 8566 1992-12-09 3000 null 20
8839 Amir President null 1991-11-18 5000 null 10
8844 Kuldeep salesman 8698 1991-09-08 1500 0 30
8886 Anoop Clerk 8888 1993-01-12 1100 null 20
8900 Jatin Clerk 8698 1991-12-03 950 null 30
8902 Fakir Analyst 8566 1991-12-03 3000 null 20
8934 Mita clerk 8882 1992-01-23 1300 null 10

show databases;

create database employee;

use employee;

create table empl(empno integer,ename varchar(20),job varchar(20),mgr


varchar(10),hiredate date,sal integer,comm varchar(10),deptno integer);

show tables;

desc empl;

insert into empl values(8369,’Smith’,’Clerk’,8902,’1990-12-


18’,800,’null’,20):

14 INSERT STATEMENTS TO BE WRITTEN BY YOU ALL IN YOUR


RECORDS

select * from empl;

2. To write Queries for the following Questions based on the given table:

a. To display all the details of table ‘empl’.

select * from empl;

b. Write a Query to Display ename, hiredate and salary.

select ename,hiredate,sal from empl;

c. Write a Query to get the name and salary of the employee whose salary is
above 1500 and job is not president.
select ename,sal from empl where sal>1500 and job<>'president';

d. Write a query to update increase 10% Salary of an employee whose


deptno is 30 and mgr is 8839.

update empl set sal=sal+(sal*0.10) where deptno=30 and


mgr=8839;

e. Write a Query to delete the details of Employee whose empno is 8934.

delete from empl where empno=8934;

3. To write queries using SQL aggregate functions, order by and group by


and having clause.

a. Write a Query to list names of Employees in Descending order.

select ename from empl order by ename desc;

b. Write a Query to find a total salary of all employees.

select sum(sal) from empl;

c. Write a Query to display maximum salary and minimum salary of


employees.

select max(sal), min(sal) from empl;

d. Write a query to display the deptno where number of


employees are greater than or equal to 3.

select deptno from empl1 group by deptno having count(*)>=3;

4. To write queries using mathematical functions, join and set


operations.

Table: student

Rollno Name Gender Age Dept DOA Percentage


1 Ankith M 16 CS 2020-04-01 98.5
2 Aadhya F 17 AI 2021-04-15 85
3 Seema F 15 IP 2021-06-01 96.8
4 Chetan M 17 IT 2022-07-12 99
5 Riya F 16 DS 2023-04-20 60.5
6 Rohan M 16 IT 2020-06-13 75.8
7 Divya F 15 CS 2021-07-10 89.8

a. Write a Query to display Remainder of column Percentage divide by 3.

Select mod(Percentage,3) from student;


b. Write a Query to display Student names and their Percentage in round
figure.

Select Name,round(Percentage,0) from student;

c. Write a Query to display student name and month of date of admission of


all students.

Select Name,month(DOA) from student;

d. Write a query to display the joining year of IP students.

Select year(DOA) from student where dept=’IP’;

e. Write a query to display the names of the students who joined in the
month of June.

select Name from student where monthname(DOA)=’June’;

f. Write a Query to display department name and its respective number of


characters in Dept column.

Select dept,length(dept) from student;

g. Write a Query to display first 2 characters of the column Name.

select right(Name,2) from student;

h. Write a query to display the names of all students and extract five
characters from the third position of the 'Name' field.

Select substr(Name,3,5) from student;


TABLE: sinfo

Rollno Grade Address Pin


1 10A Old Guntur 522001
2 9A Arundalpet 522601
3 10B Lam 522034
4 9B Gardens 522006
5 10C New Guntur 522002
6 9C SVN colony 522006
7 9A Gardens 522006

i. Write SQL query to join two tables.

select * from student,sinfo where student.Rollno=sinfo.Rollno;

(or)
select * from student s join sinfo i on(s.Rollno=i.Rollno);

ii. Write a query using table alias.

select s.Rollno,Name,Dept,Percentage,Address from student s,sinfo


where s.Rollno=sinfo.Rollno order by s.Percentage;

iii. Using SET operations


UNION
select Rollno,Name,Dept,percentage from student union select * from
sinfo;

iv. INTERSECTION
select name from vendor intersect select name from customer;

You might also like