0% found this document useful (0 votes)
36 views29 pages

Practical

Uploaded by

jahnvis102
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)
36 views29 pages

Practical

Uploaded by

jahnvis102
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/ 29

INFORMATICS PRACTICES

PRACTICAL FILE

NAME: SIDDHAM JAIN


CLASS: Xll COM B
ROLL N: 36
SUBMITTED TO: MRS.MONIKA MEHRA
PYTHON
PROGRAMMES
 PROGRAM 1: CREATING A PANDAS SEREIES
# import pandas as pd
import pandas as pd

# simple array
data = [1, 2, 3, 4]

ser = pd.Series(data)
print(ser)

 PROGRAM 2: PERFORMING MATHEMATICAL


OPERATIONS ON SERIES

# importing the module


import pandas as pd

# creating 2 Pandas Series


series1 = pd.Series([1, 2, 3, 4, 5])
series2 = pd.Series([6, 7, 8, 9, 10])

# adding the 2 Series


series3 = series1 + series2

# displaying the result


print(series3)

Output :
 PROGRAM3: COMPARISON OPERATIONS

import pandas as pd

s1 = pd.Series([1, 2, 3, 4])
s2 = pd.Series([2, 3, 4, 5])

result = s1 > s2
print(result)
This code will output:

0 False
1 False
2 False
3 False
dtype: bool

 PROGRAM 4:CREATING DATAFRAME FROM LIST

# import pandas as pd
import pandas as pd

# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']

# Calling DataFrame constructor on list


df = pd.DataFrame(lst)
df

Output:
 PROGRAM 5:ACCESSING AND SLICING
DATAFRAME

# Slicing rows in data frame


df1 = df.iloc[0:4]

# data frame after slicing


df1

Output:
 PROGRAM 6: INSERTING COLUMNS INTO
DATAFRAME

# Import pandas package


import pandas as pd

# Define a dictionary containing Students data


data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Height': [5.1, 6.2, 5.1, 5.2],
'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}

# Convert the dictionary into DataFrame


df = pd.DataFrame(data)

# Declare a list that is to be converted into a column


address = ['Delhi', 'Bangalore', 'Chennai', 'Patna']

# Using 'Address' as the column name


# and equating it to the list
df['Address'] = address

# Observe the result


print(df)

Output:
 PROGRAM 7: BINARY OPERATIONS

Adding two dataframes:


import pandas as pd

df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6],


'C': [7, 8, 9]})
df2 = pd.DataFrame({'A': [1], 'B': [2], 'C': [3]})
df1 + df2

Adding a Scalar to a DataFrame:

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6],


'C': [7, 8, 9]})

We can add a scalar value to each element in the dataframe


using broadcasting

df + 2

Multiplying Two DataFrames:

df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6],


'C': [7, 8, 9]})
df2 = pd.DataFrame({'A': [1, 2, 3]})
We can multiply the two dataframes using broadcasting:

df1 * df2
 PROGRAM 8:DROPPING ROWS AND
COLUMNS THAT MISSING VALUES

# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, np.nan, 45, 56],
'Third Score':[52, 40, 80, 98],
'Fourth Score':[np.nan, np.nan, np.nan, 65]}

# creating a dataframe from dictionary


df = pd.DataFrame(dict)

# using dropna() function


df.dropna()

Output:
 PROGRAM 9: FILLING MISSING VALUES

# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, 45, 56, np.nan],
'Third Score':[np.nan, 40, 80, 98]}

# creating a dataframe from dictionary


df = pd.DataFrame(dict)

# filling missing value using fillna()


df.fillna(0)

OUTPUT:
 PROGRAM 10: CREATING AND READING CSV
FILE

import csv

# opening the CSV file


with pd.read_csv ('Giants.csv', mode ='r')as file:

# reading the CSV file


csvFile = csv.reader(file)

# displaying the contents of the CSV file


for lines in csvFile:
print(lines)
Output:
[['Steve', 13, 'A'],
['John', 14, 'F'],
['Nancy', 14, 'C'],
['Ravi', 13, 'B']]
 PROGRAM 11: SAVING DATAFRAME AS CSV
FILE

# importing pandas as pd
import pandas as pd

# list of name, degree, score


nme = ["aparna", "pankaj", "sudhir", "Geeku"]
deg = ["MBA", "BCA", "M.Tech", "MBA"]
scr = [90, 40, 80, 98]

# dictionary of lists
dict = {'name': nme, 'degree': deg, 'score': scr}

df = pd.DataFrame(dict)

print(df)

Output:
name degree score
0 aparna MBA 90
1 pankaj BCA 40
2 sudhir M.Tech 80
3 Geeku MBA 98
Here, we simply export a Dataframe to a CSV file using df.to_csv()
# saving the dataframe
df.to_csv('file1.csv')
 PROGRAM 12: CREATING AND SHOWING SIMPLE
LINE PLOT

# importing the required libraries


import matplotlib.pyplot as plt
import numpy as np

# define data values


x = np.array([1, 2, 3, 4]) # X-axis points
y = x*2 # Y-axis points

plt.plot(x, y) # Plot the chart


plt.show() # display

OUTPUT:
 PROGRAM 13: PLOTTING DATAFRAMES ON BAR CHART

# importing pandas library


import pandas as pd
# import matplotlib library
import matplotlib.pyplot as plt

# creating dataframe
df = pd.DataFrame({
'Name': ['John', 'Sammy', 'Joe'],
'Age': [45, 38, 90],
'Height(in cm)': [150, 180, 160]
})

# plotting graph
df.plot(x="Name", y=["Age", "Height(in cm)"],
kind="bar")

OUTPUT:
 PROGRAM 14: PLOTTING HISTOGRAMS

from matplotlib import pyplot as plt


import numpy as np

# Creating dataset
a = np.array([22, 87, 5, 43, 56,
73, 55, 54, 11,
20, 51, 5, 79, 31,
27])

# Creating histogram
fig, ax = plt.subplots(figsize =(10, 7))
ax.hist(a, bins = [0, 25, 50, 75, 100])

# Show plot
plt.show()

OUTPUT:
MY SQL QUERIES
 PRACTICAL 1: ASSIGNING PRIMARY KEY

QUERY:

OUTPUT:
 PRACTICAL 2: FOREIGN KEY

Consider The following customer relationship

Customer_id Customer_name Customer_Address

101 Geek 1 Chennai

102 Geek 2 Delhi

103 Geek 3 Bombay

104 Geek 4 Pune

105 Geek 5 Nashik

In order to create the following table, we use the following command

CREATE TABLE Customer(

Customer_id int primary key,

Customer_name varchar(20),

Customer_Address varchar(20),

Now Consider the Sales relation,


Customer_id Item_Id Payment_Mode

101 1334151 COD

101 16652 Debit Card

104 1009 Paypal

102 14543 COD

So in this relation, Customer_id is a foreign key that is obtained from the above
customer relation. We can create the table using the following command.
CREATE TABLE SALES(
Customer_id int FOREIGN KEY REFERENCES Customer(Customer_id)
Item_id int,
Payment_Mode varchar(20),
 PRACTICAL 3 : THE SELECT OPERATION

 CONSIDER TABLE CUSTOMER


Query to fetch the fields CustomerName, LastName from the table Customer:

SELECT CustomerName, LastName FROM Customer;

OUTPUT:

To
fetch
all the fields from the table Customer:
SELECT * FROM Customer;

OUTPUT:
 PRACTICAL 4: CARTESIAN PRODUCT

CONSIDER TWO TABLES :

STUDENT COURSE

QUERY: SELECT Student.NAME, Student.AGE, StudentCourse.COURSE_ID


FROM Student
CROSS JOIN StudentCourse;

 OUTPUT:
 PRACTICAL 5 : WHERE CLAUSE

CREATE TABLE Emp1(


EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
mob int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Emp1 (EmpID, Name,Country, Age, mob)
VALUES (1, 'Shubham', 'India','23','738479734'),
(2, 'Aman ', 'Australia','21','436789555'),
(3, 'Naveen', 'Sri lanka','24','34873847'),
(4, 'Aditya', 'Austria','21','328440934'),
(5, 'Nishant', 'Spain','22','73248679');
Select * from Emp1;
Query:
SELECT * FROM Emp1 WHERE Age=24;
Output:

To fetch the EmpID, Name and Country of Employees with Age greater than
21.
Query:
SELECT EmpID, Name, Country FROM Emp1 WHERE Age > 21;
Output:
 PRACTICAL 6: THE DISTINCT
CLAUSE

CONSIDER TABLE STUDENT

Now, to
fetch unique names from the NAME field.
Query:
SELECT DISTINCT NAME FROM Student;

OUTPUT:

Now, to fetch a unique combination of rows from the whole table.


Query:
SELECT DISTINCT * FROM students;
Output:
 PRACTICAL 7: THE BETWEEN & AND
OPERATOR

CONSIDER TABLE EMP:

List all the Employee’s Names who is having salary between 30000 and 45000.
Query:
SELECT Name
FROM Emp
WHERE Salary
BETWEEN 30000 AND 45000;

Output:
 PRACTICAL 8: THE LIKE OPERATOR

we have a relation, Supplier. We want to test various patterns using the LIKE clause:
Supplier Table
SupplierID Name Address

S1 Paragon Suppliers 21-3, Okhla, Delhi

S2 Mango Nation 21, Faridabad, Haryana

S3 Canadian Biz 6/7, Okhla Phase II, Delhi

S4 Caravan Traders 2-A, Pitampura, Delhi

S5 Harish and Sons Gurgaon, NCR

S6 Om Suppliers 2/1, Faridabad, Haryana

Query :

SELECT SupplierID, Name, Address


FROM Suppliers
WHERE Name LIKE 'Ca%';
Output:
S3 Canadian Biz 6/7, Okhla Phase II, Delhi

S4 Caravan Traders 2-A, Pitampura, Delhi

 PRACTICAL 9: THE UPDATE COMMAND


CONSIDER TABLE CUSTOMER:

Update the column NAME and set the value to ‘Nitin’ in the rows where the Age
is 22.
UPDATE Customer SET CustomerName
= 'Nitin' WHERE Age = 22;
Output:
 PRACTICAL 10: GROUP BY FUNCTION

CONSIDER TABLE EMP:

Query:
SELECT NAME, SUM(SALARY) FROM emp
GROUP BY NAME;

The above query will produce the below output:


 PRACTICAL 11: HAVING CLAUSE

CONSIDER TABLE STUDENT:

Execute Query
SELECT student, percentage
FROM Student
GROUP BY student, percentage
HAVING percentage > 95;
Here, three students named Isha, Sumedha, and Rahat Ali scored more than 95
%.

Output:
 PRACTICAL 12 : USING STRING
FUNCTIONS

 CHAR_LENGTH():
QUERY: SELECT char_length('Hello!');
Output: 6

 INSTR():
QUERY: INSTR('geeks for geeks', 'e');
Output: 2 (the first occurrence of ‘e’)

 LCASE():
QUERY: LCASE ("GeeksFor Geeks To Learn");
Output: geeksforgeeks to learn

 LENGTH():
QUERY: LENGTH('GeeksForGeeks');
Output: 13

 LTRIM():
QUERY: LTRIM('123123geeks', '123');
Output: geeks

 RTRIM():
QUERY: RTRIM('geeksxyxzyyy', 'xyz');
Output: ‘geeks’
 PRACTICAL 13: USING IN OPERATOR

CONSIDER TABLE EMP:

Find the Fname, and Lname of the Employees who have a Salary equal to 30000,
40000, or 25000.
Query:
SELECT Name
FROM Emp
WHERE Salary IN (30000, 40000, 25000);
Output:
 PRACTICAL 14 : USING ALL OPERATOR

Consider the following Products Table and OrderDetails Table,Products Table

 Find the name of the all the product.


SELECT ALL ProductName
FROM Products
WHERE TRUE;
OUTPUT:

You might also like