Professional Documents
Culture Documents
2) Create a series of these numbers: 33,55,65,29,19,23. Find the sum of those values which
are ending with 3 or 5.
#Solution
import pandas as pd
list=[33,55,65,29,19,23]
ser=pd.Series(list)
sumall=0
sum5=sum(ser[ser%10==5])
sum3=sum(ser[ser%10==3])
sumall=sum5+sum3
print(“Sum=”,sumall)
import pandas as pd
ser=pd.Series(range(41,71,3))
for i in range(0,ser.size):
if (ser[i]%2==0):
ser[i]=ser[i]-3
else:
ser[i]=ser[i]+7
print(ser)
5) Create a series and print the top 3 elements using the head function and bottom 4 element using tail
function
#Solution
import pandas as pd
ser=pd.Series(range(3,71,7))
print("Top 3 Elements are ")
print(ser.head(3))
print("Bottom 4 Elements are ")
print(ser.tail(4))
print("1. Addition")
print("2. Substraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
ch=int(input("Enter choice:"))
if ch==1:
print(S+S1)
elif ch==2:
print(S-S1)
elif ch==3:
print(S*S1)
elif ch==4:
print(S/S1)
elif ch==5:
break
8) Given a Series, print all the elements that are above the 75th percentile.
#Solution
import pandas as pd
lst=[10,20,30,45,75,63,72,78]
s=pd.Series(lst)
print(s[s>s.quantile(.75)])
9) Create a data frame for examination results and display row labels, column labels, data types of each
column and the dimensions.
#Solution
import pandas as pd
res={'Amit':[76,78,75,66,68], 'Shialesh':[78,56,77,49,55], 'Rani':[90,91,93,97,99], 'Madan':[55,48,59,60,66],
'Radhika':[78,79,85,88,86]}
df=pd.DataFrame(res)
print("Prinitng row labels in a list:")
idx=df.index
print(idx)
print("Prinitng row labels in a list:")
for col in df.columns:
print(col,end=" ")
print("Printing Data Types of each column")
print(df.dtypes)
print("Printing dimensions of Data Frame")
print(df.ndim)
8) Create a dataframe players using a list of names and scores of the previous three
matches. (Using Nested list)
import pandas as pd
data=[["Virat",56,66,31],["Rohit",88,66,43],["Dhoni",75,54,56]]
players=pd.DataFrame(data,columns=["Name","M1","M2","M3"])
print(players)
#Solution
import pandas as pd
dict1={'Rollno':['10E01','12E05','10E12','12E15','10E25'],
'Name':['AMAN','RAGHAV','RISHI','MANVI','VIVEK'], 'Year':[1982,1984,1982,1984,1982],
'Percentage':[98.5,86.9,76.6,80.0,87.5]}
df=pd.DataFrame(dict1)
print(df)
print("Index=",df.index)
print("columns=",df.columns)
print(df.shape)
print("Size : ",df.size)
print("Axes :",df.axes)
print("Rows :",df.values)
print("Columns :",df.columns)
12) Write a python program to do the following to the dataframe:-
Rollno Name Year Percentage
10E01 AMAN 1982 98.5
12E05 RAGHAV 1984 86.9
10E12 RISHI 1982 76.6
12E15 MANVI 1984 80.0
10E25 VIVEK 1982 87.5
a. Create the above dataframe
b. Add a column name class and insert 12 in all of the rows
c. Rename the name column as Student_Name.
d. Drop the column class
e. Use loc and iloc function to access 3rd to 5th row and name and percentage column
f. Update the name value of RollNo 10E12 to Mukesh using at and iat function
#Solution
# Creating the above dataframe.
import pandas as pd
dict1={'Rollno':['10E01','12E05','10E12','12E15','10E25'],
'Name':['AMAN','RAGHAV','RISHI','MANVI','VIVEK'], 'Year':[1982,1984,1982,1984,1982],
'Percentage':[98.5,86.9,76.6,80.0,87.5]}
df=pd.DataFrame(dict1)
print(df)
# Adding column name class
df[„class‟]=12
# Renaming the column
df.rename(columns={„Name‟:”Student_Name”},inplace=True)
# Dropping the column class
df.drop(„class‟,axis=1)
# Using loc and iloc
df.loc[2:4,[„Name‟,‟Percentage‟]]
df.iloc[2:5,[1,3]]
# Updating using at and iat
df.at[2,‟Name‟]=”Mukesh”
df.iat[2,1]=”Mukesh”
13) Create a dataframe named cricket having score given in odi, test and T20 matches. Display the
batsman details who scored
a. More than 2000 in ODI
b. Less than 2500 in Test
c. More than 1500 in T20
#Solution
import pandas as pd
data={"Name":["Virat","Rohit","Dhoni","Yuvraj"],
"Test":[3543,2578,2280,3625],
"ODI":[2845,2665,2580,2280],
"T20":[1925,1586,1890,1635]}
cricket=pd.DataFrame(data)
#run more tahn 2500 in ODI
print(cricket.loc[cricket["ODI"]>2500,["Name"]])
#run more than 2000 in T20
print(cricket.loc[cricket["T20"]>2000,["Name"]])
#run more than 2200 in Test
print(cricket.loc[cricket["Test"]>2200,["Name"]])
14) Write a python program to import data from a csv file and after adding a column to it write again to
the csv file.
import pandas as pd
print(“Importing data from csv file”)
df=pd.read_csv(“d:\\sample.csv”,header=None,names=[„RN‟,‟Name‟,‟Class‟],nrows=10)
print(df)
df[„city‟]=”Neemuch”
print(“DataFrame after column addition”)
print(df)
df.to_csv(“d:\\sample.csv”,sep=”;”,na_rep=”NULL”)
print(“Data Written to CSV file successfully”)
15) Write a python program to import data from mysql table into dataframe using sqlalchemy.
#Solution
import pandas as pd
import sqlalchemy as sq
import pymysql
engine=sq.create_engine(“mysql+pymsql://root:root123@localhost/cbse’)
con=engine.connect()
df=pd.read_sql(“Select *from Student”,con)
print(df)
#MATPLOTLIB
16) Plot the following data on a line chart and customize the chart according to the below-given
instructions:
#Solution
import matplotlib.pyplot as pp
day =['Monday','Tuesday','Wednesday','Thursday','Friday']
ct = [450,560,400,605,580] js = [490,600,425,610,625]
pp.plot(day,ct,label='Cotton',color='g',linestyle='dotted',marker='+')
pp.plot(day,js,label='Food',color='m',linestyle='dashdot',marker='x')
pp.title("The Weekly Garment Orders")
pp.xlabel("Days")
pp.ylabel("Orders")
pp.legend()
pp.show()
18) Observe the given data for monthly views of one of the youtube channels for 6 months. Plot them on
the line chart.
Month January February March April May June
#Solution
import matplotlib.pyplot as pp
mon =['January','February','March','April','May','June']
views = [2500,2100,1700,3500,3000,3800]
pp.bar(mon,views,width=.5,color=[„r‟,‟g‟,‟b‟,‟c‟,‟m‟,‟y‟])
pp.title("Youtube Stats")
pp.xlabel("Months")
pp.ylabel("Views")
pp.legend()
19) Draw to bar chart showing the comparison of two teams score in 5 overs, giving the proper title ,
xlabel , ylabel and legend.
#Solution
import matplotlib.pyplot as pt
import numpy as np
overs=np.array([1,2,3,4,5])
team1=[3,8,4,6,5]
team2=[6,2,9,5,3]
pt.bar(overs,team1,width=.3,color=‟g‟,label=”Team A”)
pt.bar(overs+.3,team2,width=.3,color=‟r‟,label=”Team B”)
pt.legend()
pt.xlabel(“Overs”)
pt.ylabel(“Runs”)
pt.title(“Run rate comparision”)
pt.show()
20) Create a histogram from the data given for the students in class XII,
#Solution
import matplotlib.pyplot as pt
x=[23,54,76,90,59,87,67,49,93]
pt.hist(x,bins=[0,33,50,80,100]
pt.title(“Histogram for showing the distribution of Marks of Student”)
pt.xlable(“Marks Range”)
pt.ylabel(“No. of Student Scored”)
pt.show()
MYSQL/SQL QUERIES
1. Create a database with name CBSE.
Ans) CREATE DATABASE CBSE.
2. Display all the databases available in your system.
Ans) SHOW DATABASES;
3. Select the database cbse which is created in the above query.
Ans) USE CBSE;
4. Create a student table with the student id, name, and marks as attributes where the student id is the
primary key.
Ans) CREATE TABLE STUDENT(ID INT PRIMARY KEY, NAME CHAR(30), MARKS INT NOT NULL);
5. Insert the details of a new student in the above table.
Ans) INSERT INTO STUDENT VALUES(101,’AMAN’,96);
INSERT INTO STUDENT VALUES(102,’SOHAN’,86);
INSERT INTO STUDENT VALUES(103,’ROHAN’,72);
INSERT INTO STUDENT VALUES(104,’KARAN’,81);
INSERT INTO STUDENT VALUES(105,’MUKESH’,66);
INSERT INTO STUDENT VALUES(106,’BALKISHAN’,70);
6. Delete the details of a student in the above table.
Ans) DELETE FROM STUDENT WHERE RN=102;
DELETE FROM STUDENT WHERE NAME=’KARAN’;
7. Use the select command to get the details of the students with marks more than 80.
Ans) SELECT *FROM STUDENT WHERE MARK>80;
8. Find the min, max, sum, and average of the marks in a student marks table.
Ans) SELECT MIN(MARKS),MAX(MARKS),SUM(MARKS),AVG(MARKS) FROM STUDENT;
9. Consider a table with name customer having attributes as (customer ID, customer
Name, country) Find the total number of customers from each country in the table.
Ans) SELECT COUNTRY,COUNT(CUSTOMER_NAME) FROM CUSTOMER GROUP BY COUNTRY;
10. Write a SQL query to order the (student ID, marks) table in descending order of the marks.
Ans) SELECT * FROM STUDENT ORDER BY STUDENT_ID DESC, MARKS DESC;
11. Write a SQL query to display the marks without decimal places, display the reminder after diving marks by
3 and display the square of marks.
Ans) SELECT ROUND(MARKS),MOD(MARKS,3),POWER(MARKS,2) FROM STUDENT;
12. Write a SQL query to display names into capital letters, small letters, display frist 3 letters of name, display
last 3 letters of name, display the position the letter A in name.
Ans) SELECT UPPER(NAME), LOWER(NAME), LEFT(NAME,3), RIGHT(NAME,3),INSTR(NAME,’A’) FROM
STUDENT
13. Remove extra spaces from left, right and both sidesfrom the text – ” Informatics Practices Class XII “.
Ans) SELECT LTRIM(” Informatics Practices Class XII “);
SELECT RTRIM(” Informatics Practices Class XII “);
SELECT TRIM(” Informatics Practices Class XII “);
14. Display today’s date in “Date/Month/Year” format.
Ans) SELECT date_format(now( ), ‘%d/%m/%Y’);
15. Display dayname, monthname, day, day of week for today’s date.
Ans) SELECT DAYNAME(NOW( ));
SELECT MONTHNAME(NOW ( ));
SELECT DAY(NOW( ));
SELECT DAYOFWEEK(NOW ( ));
16. Create following table: EMP,
Ans) CREATE TABLE Employee (EID INT PRIMARY KEY, NAME VARCHAR(20), DEPT VARCHAR(20), GEN
CHAR(1), SALARY DECIMAL(10,2), DOJ DATE);
17. Insert Some records into the employee table as per your choice-
INSERT INTO Employee VALUES (1,'RASHI','COMPUTER','F',185000.00,'2010-01- 01');
INSERT INTO Employee VALUES (2,'RISHIKA','ACCOUNTS','F',115000.00,'2015-07- 01');
INSERT INTO Employee VALUES ( 3,'AKSHIT','SALES','M',125000.00,'2015-07- 01');
INSERT INTO Employee VALUES (4,'MOHIT','SALES','M',105000.00,'2015-01- 15');
INSERT INTO Employee VALUES (5,'TAPPU','ACCOUNTS','M',55000.00,'2015-01- 27');
INSERT INTO Employee VALUES (6,'SAHIL','COMPUTER','M',125000.00,'2018-07-02');
18. Show all data of table
Ans) Select *from employee;
EID NAME DEPT GEN SALARY DOJ
1 RASHI COMPUTER F 185000 01/01/2010
2 RISHIKA ACCOUNTS F 115000 01/07/2015
3 AKSHIT SALES M 125000 01/07/2015
4 MOHIT SALES M 105000 15/01/2015
5 TAPPU ACCOUNTS M 550000 27/01/2015
6 SAHIL COMPUTER M 125000 02/07/2018