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

Class 12 Practical File

The documents provide examples of using Python and Pandas to work with dataframes and series. This includes creating, manipulating, selecting and plotting data from series and dataframes. Various functions like iterrows, iteritems and plotting charts with matplotlib are also demonstrated.

Uploaded by

hemant_sangeeta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Class 12 Practical File

The documents provide examples of using Python and Pandas to work with dataframes and series. This includes creating, manipulating, selecting and plotting data from series and dataframes. Various functions like iterrows, iteritems and plotting charts with matplotlib are also demonstrated.

Uploaded by

hemant_sangeeta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Index for Python Programs

1. Create an Empty Series


2. Create a Panda Series from an Array.
3. Create a Panda Series from an Array with Index.
4. Create a Series from Dictionary
5. Create a Series from Dictionary with Index.
6. Create a Series from Scalar
7. Accessing Data from Series with Position
8. Retrieve Data Using Label (Index)
9. Create an Empty DataFrame
10. Create a DataFrame from Lists
11. Create a DataFrame from Dict of Lists
12. Create a DataFrame from List of Dicts
13. Create a DataFrame from Dict of Series
14. Column Selection in DataFrame
15. Column Addition in DataFrame
16. Column Deletion in DataFrame
17. Using Iterrows function in DataFrame
18. Using Iteritems function in DataFrame
19. Create chart using matplotlib.pyplot
20. Show date and temperature in chart using matplotlib.pyplot
21. Show chart using line chart with different colours.
22. Show chart using histogram chart.

Index for SQL Commands


1. Create database
2. Create table Employee_Info
3. Create a table using another table.
4. To drop an existing a database.
5. To drop an existing table.
6. Delete the table.
7. ADD Column bloodgroup:
8. DROP Column bloodgroup:
9. Create table Employee_Info using Not Null
10. Alter table using Not Null
11. Using constraint ensures that all the values in a column are unique
12. UNIQUE on Multiple Columns
13. UNIQUE on ALTER TABLE
14. Insert values in table
15. The conditions separated by OR
16. The NOT operator is used.
17. Combine all logical operator
18. The BETWEEN operator is used
19. The LIKE operator is used
20. To specify multiple values in a WHERE clause.
21. The MIN function
22. The MAX function
23. The COUNT function
24. The SUM function
25. The AVG function
26. Aliases are used
27. Use of order by
28. Use of order by for descending order
29. Delete command
30. Write a python program to create database hps and table emp
31. Write a python program to insert value in table employee
32. Write a program to display all records from emp

# 1. Create an Empty Series


import pandas as pd
s = pd.Series()
print (s)

output: Series([], dtype: float64)

# 2. Create a Panda Series from an Array.


import pandas as pd
import numpy as np
data=np.array(['a','b','c','d'])
s =pd.Series(data)
print (s)

output:
0 a
1 b
2 c
3 d
dtype: object

#3. Create a Panda Series from an Array with Index.


import pandas as pd
import numpy as np
data=np.array(['a','b','c','d'])
s =pd.Series(data,index=[100,101,102,103])
print (s)

output:
100 a
101 b
102 c
103 d
dtype: object

# 4. Create a Series from Dictionary

import pandas as pd
import numpy as np
data={'a':0.,'b':1.,'c':2.}
s =pd.Series(data)
print (s)

output:
a 0.0
b 1.0
c 2.0
dtype: float64

# 5. Create a Series from Dictionary with Index.

import pandas as pd
import numpy as np
data={'a':0.,'b':1.,'c':2.}
s =pd.Series(data,index=['b','c','d','a'])
print (s)

output:
b 1.0
c 2.0
d NaN
a 0.0
dtype: float64

# 6. Create a Series from Scalar


#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
s =pd.Series(5, index=[0,1,2,3])
print (s)

output:
0 5
1 5
2 5
3 5
dtype: int64

# 7. Accessing Data from Series with Position


import pandas as pd
s =pd.Series([1,2,3,4,5],index =['a','b','c','d','e'])
#retrieve the first element
print (s[0])

output:
1

import pandas as pd
s =pd.Series([1,2,3,4,5],index =['a','b','c','d','e'])
#retrieve the first three element
print (s[:3])

output:
a 1
b 2
c 3
dtype: int64

import pandas as pd
s =pd.Series([1,2,3,4,5],index =['a','b','c','d','e'])
#retrieve the last three element
print (s[-3:])

output:
c 3
d 4
e 5
dtype: int64

# 8. Retrieve Data Using Label (Index)


import pandas as pd
s =pd.Series([1,2,3,4,5],index =['a','b','c','d','e'])
#retrieve a single element
print (s['a'])

output:
1

import pandas as pd
s =pd.Series([1,2,3,4,5],index =['a','b','c','d','e'])
#retrieve multiple elements
print (s[['a','c','e']])

output:
a 1
c 3
e 5
dtype: int64

# 9. Create an Empty DataFrame


#import the pandas library and aliasing as pd
import pandas as pd
df = pd.DataFrame()
print (df)

output:
Empty DataFrame
Columns: []
Index: []

#10. Create a DataFrame from Lists


import pandas as pd
data=[1,2,3,4,5]
df=pd.DataFrame(data)
print (df)

output:
0
0 1
1 2
2 3
3 4
4 5
import pandas as pd
data=[['Alex',10],['Bob',12],['Clarke',13]]
df=pd.DataFrame(data,columns=['Name','Age'])
print (df)

output:
Name Age
0 Alex 10
1 Bob 12
2 Clarke 13

#11. Create a DataFrame from Dict of Lists


import pandas as pd
data={'Name':['Tom','Jack','Steve','Ricky'],'Age':[28,34,29,42]}
df=pd.DataFrame(data)
print (df)

output:
Name Age
0 Tom 28
1 Jack 34
2 Steve 29
3 Ricky 42

import pandas as pd
data={'Name':['Tom','Jack','Steve','Ricky'],'Age':[28,34,29,42]}
df=pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])
print (df)

output:
Name Age
rank1 Tom 28
rank2 Jack 34
rank3 Steve 29
rank4 Ricky 42

#12. Create a DataFrame from List of Dicts


import pandas as pd
data=[{'a':1,'b':2},{'a':5,'b':10,'c':20}]
df=pd.DataFrame(data)
print (df)
output:
a b c
0 1 2 NaN
1 5 10 20.0

#13. Create a DataFrame from Dict of Series


import pandas as pd

d ={'one':pd.Series([1,2,3], index=['a','b','c']),'two':pd.Series([1,2,3,4], index=['a','b','c','d'])}

df=pd.DataFrame(d)
print (df)

output:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4

#14. Column Selection in DataFrame


import pandas as pd
d ={'one':pd.Series([1,2,3], index=['a','b','c']),'two':pd.Series([1,2,3,4], index=['a','b','c','d'])}

df=pd.DataFrame(d)
print (df['one'])

output:
a 1.0
b 2.0
c 3.0
d NaN
Name: one, dtype: float64

#15. Column Addition in DataFrame


import pandas as pd

d ={'one':pd.Series([1,2,3], index=['a','b','c']),
'two':pd.Series([1,2,3,4], index=['a','b','c','d'])}
df=pd.DataFrame(d)

# Adding a new column to an existing DataFrame object with column label by passing new
series

print("Adding a new column by passing as Series:")


df['three']=pd.Series([10,20,30],index=['a','b','c'])
print (df)

print("Adding a new column using the existing columns in DataFrame:")


df['four']=df['one']+df['three']

print (df)

output:
Adding a new column by passing as Series:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN
Adding a new column using the existing columns in DataFrame:
one two three four
a 1.0 1 10.0 11.0
b 2.0 2 20.0 22.0
c 3.0 3 30.0 33.0
d NaN 4 NaN NaN

#16. Column Deletion in DataFrame


# Using the previous DataFrame, we will delete a column
# using del function
import pandas as pd

d ={'one':pd.Series([1,2,3], index=['a','b','c']),
'two':pd.Series([1,2,3,4], index=['a','b','c','d']),
'three':pd.Series([10,20,30], index=['a','b','c'])}

df=pd.DataFrame(d)
print("Our dataframe is:")
print(df)

# using del function


print("Deleting the first column using DEL function:")
del df['one']
print (df)

# using pop function


print("Deleting another column using POP function:")
df.pop('two')
print (df)
output:
Our dataframe is:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN
Deleting the first column using DEL function:
two three
a 1 10.0
b 2 20.0
c 3 30.0
d 4 NaN
Deleting another column using POP function:
three
a 10.0
b 20.0
c 30.0
d NaN

#17.Using ITERROWS FUNCTION in DataFrame


import pandas as pd
marks={2018:{'English':98,'Physics':99,'Chemistry':100,
'Biology':100,'Maths':100,'CS':100},
2019:{'English':99,'Physics':97,'Chemistry':99,
'Biology':100,'Maths':100,'CS':99},
2020:{'English':97,'Physics':98,'Chemistry':98,
'Biology':98,'Maths':99,'CS':96},
}
df1=pd.DataFrame(marks)
for i, row in df1.iterrows():
print("-----------------------")
print(row)
output:
2018 98
2019 99

2020 97
Name: English, dtype: int64
-----------------------
2018 99
2019 97

2020 98
Name: Physics, dtype: int64
-----------------------
2018 100
2019 99

2020 98
Name: Chemistry, dtype: int64
-----------------------
2018 100
2019 100

2020 98
Name: Biology, dtype: int64
-----------------------
2018 100
2019 100

2020 99
Name: Maths, dtype: int64
-----------------------
2018 100
2019 99
2020 96
Name: CS, dtype: int64

#18. Using DataFrame.iteritems()


#Import Panda module
import pandas as panda
#Data in columns
data = {
"Student_Name": ["Sally", "Anna", "Ryan"],
"Age": [15, 16, 17],
"Class": ["Maths" , "English" , "French"]
}
#Dataframe object
dataframe = panda.DataFrame(data)
#Iteration for columns label and its contents
for Label, Content in dataframe.iteritems():
# column name
print(Label)
# column content
print(Content)
output:
Student_Name

0 Sally
1 Anna
2 Ryan
Name: Student_Name, dtype: object
Age

0 15
1 16
2 17
Name: Age, dtype: int64
Class
0 Maths
1 English

2 French
Name: Class, dtype: object
_______________________________________________________________________________

#19. Create chart using matplotlib.pyplot


import matplotlib.pyplot as plt
time = [0, 1, 2, 3]
position = [0, 100, 200, 300]
plt.plot(time, position)
plt.xlabel('Time (hr)')
plt.ylabel('Position (km)')
plt.show()

output:

______________________________________________________________________
#20. Show date and temperature in chart using matplotlib.pyplot
#Plotting Temperature against Height
import matplotlib.pyplot as plt
#list storing date in string format
date=["25/12","26/12","27/12"]
#list storing temperature values
temp=[8.5,10.5,6.8]
#create a figure plotting temp versus date
plt.plot(date, temp)
#show the figure
plt.show()

"""Plotting a line chart of date versus temperature by adding Label on X and Y axis, and adding
a Title and Grids to the chart."""
import matplotlib.pyplot as plt
date=["25/12","26/12","27/12"]
temp=[8.5,10.5,6.8]
plt.plot(date, temp)
plt.xlabel("Date") #add the Label on x-axis
plt.ylabel("Temperature") #add the Label on y-axis
plt.title("Date wise Temperature") #add the title to the chart
plt.grid(True) #add gridlines to the background
plt.yticks(temp)
plt.show()
output:

#21. Show chart using line chart with different colours.


#kind=>line,bar,barh,hist,box,area,pie,scatter
#Line colours are red for week 1, blue for week 2 and brown for week 3.
import pandas as pd
import matplotlib.pyplot as plt
# reads "MelaSales.csv" to df by giving path to the file
#df=pd.read_csv("weekData.csv")
d1={'week1':[5000,6000,3000,3500,2000],'week2':[4800,2300,2000,6500,5000],'week3':[3000,5
500,2800,4500,2500]}
df=pd.DataFrame(d1)
#create a line plot of different color for each week
df.plot(kind='line', color=['red','blue','brown'])
# Set title to "Mela Sales Report"
plt.title('Mela Sales Report')
# Label x axis as "Days"
plt.xlabel('Days')
# Label y axis as "Sales in Rs"
plt.ylabel('Sales in Rs')
#Display the figure
plt.show()

output:

Plotting Histogram Histograms are column-charts, where each column represents a range of values, and
the height of a column corresponds to how many values are in that range.

#22. Show chart using histogram chart.


import pandas as pd
import matplotlib.pyplot as plt
import pandas as pd
data = {'Name':['Arnav', 'Sheela', 'Azhar', 'Bincy', 'Yash','Nazar'],
'Height' : [60,50,60,40,55,30],
'Weight' : [70,90,80,90,80,80]}

df=pd.DataFrame(data)
df.plot(kind='hist')
plt.show()

output:

import pandas as pd
marksUT= {'Name':['Raman','Raman','Raman','Zuhaire','Zuhaire','Zuhaire',
'Ashravy','Ashravy','Ashravy','Mishti','Mishti','Mishti'],
'UT':[1,2,3,1,2,3,1,2,3,1,2,3],
'Maths':[22,21,14,20,23,22,23,24,12,15,18,17],
'Science':[21,20,19,17,15,18,19,22,25,22,21,18],
'S.St':[18,17,15,22,21,19,20,24,19,25,25,20],
'Hindi':[20,22,24,24,25,23,24,17,25,25,24,25],
'Eng':[21,24,23,19,15,13,22,21,23,22,23,20]
}
df=pd.DataFrame(marksUT)
print("Max")
print(df.max(numeric_only=True)) #Find out maximum value numeric only
print("Min")
print(df.min(numeric_only=True)) #Find out miminum value
print("Sum")
print(df.sum(numeric_only=True)) #Calculate sum of values
print("Mean")
print(df.mean(numeric_only=True))#Calculate Average Value
print("Median")
print(df.median(numeric_only=True))#Find out middle value
print("Mode")
print(df.mode(numeric_only=True)) #Find out mode value
print("Standand deviation")
print(df.std(numeric_only=True))# Find out standard deviation
print("Describe ")
print(df.describe())

output:
Max

UT 3
Maths 24
Science 25
S.St 25
Hindi 25

Eng 24
dtype: int64
Min
UT 1
Maths 12

Science 15
S.St 15
Hindi 17
Eng 13
dtype: int64
Sum

UT 24
Maths 231
Science 237
S.St 245
Hindi 278

Eng 246
dtype: int64
Mean
UT 2.000000
Maths 19.250000

Science 19.750000
S.St 20.416667
Hindi 23.166667
Eng 20.500000
dtype: float64

Median
UT 2.0
Maths 20.5
Science 19.5
S.St 20.0

Hindi 24.0
Eng 21.5
dtype: float64
Mode
UT Maths Science S.St Hindi Eng
0 1.0 22.0 18 19.0 24.0 23.0
1 2.0 23.0 19 20.0 25.0 NaN
2 3.0 NaN 21 25.0 NaN NaN
3 NaN NaN 22 NaN NaN NaN

Standand deviation
UT 0.852803
Maths 3.980064
Science 2.667140
S.St 3.146667

Hindi 2.443296
Eng 3.370999
dtype: float64
Describe
UT Maths Science S.St Hindi Eng

count 12.000000 12.000000 12.00000 12.000000 12.000000 12.000000


mean 2.000000 19.250000 19.75000 20.416667 23.166667 20.500000
std 0.852803 3.980064 2.66714 3.146667 2.443296 3.370999
min 1.000000 12.000000 15.00000 15.000000 17.000000 13.000000
25% 1.000000 16.500000 18.00000 18.750000 22.750000 19.750000

50% 2.000000 20.500000 19.50000 20.000000 24.000000 21.500000


75% 3.000000 22.250000 21.25000 22.500000 25.000000 23.000000
max 3.000000 s24.000000 25.00000 25.000000 25.000000 24.000000
_____________________________________________________________________________________

1 CREATE DATABASE Employee; to create a database.


2

Output: Query OK, 0 rows affected (1.30 sec)

3 create a table using another table.

4 to drop an existing a database.

to drop an existing table.

6 This command is used to delete


the information present in the
table but does not delete the table.

7 ADD Column BloodGroup:

8 DROP Column BloodGroup:


9 NOT NULL on Create Table

NOT NULL on ALTER TABLE


10

11 This constraint ensures that all the


values in a column are unique.

12 UNIQUE on Multiple Columns

13 UNIQUE on ALTER TABLE


14

14

This operator is used to filter records that rely on more than one condition.
15

This operator displays all those records which satisfy any of the conditions separated by OR and give the
output TRUE.
16

The NOT operator is used, when you want to display the records which do not satisfy a
condition.
17

Combine all logical operator


18

The BETWEEN operator is used, when you want to select values within a given range.
19

The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column of a table. There are mainly two wildcards that are used in conjunction with the
LIKE operator:
% – It matches 0 or more character.
_ – It matches exactly one character.

20

This operator is used for multiple OR conditions. This allows you to specify multiple
values in a WHERE clause.
21

The MIN function returns the smallest value of the selected column in a table.
22

The MAX function returns the largest value of the selected column in a table.
23

The COUNT function returns the number of rows which match the specified criteria.

24
The SUM function returns the total sum of a numeric column that you choose.
25

The AVG function returns the average value of a numeric column that you choose.
27

Aliases are used to give a column/table a temporary name and only exists for a duration of
the query.
28

29

30

31. Write a python program to create database hps and table emp
import mysql.connector as sql
import pandas as pd
con=sql.connect(user='root',password='root',host='localhost')
cur=con.cursor()
cur.execute('create database if not exists raath')
cur.execute('use raath')
cur.execute('create table if not exists emp(code char(4), name varchar(40), salary int)')
cur.execute('show tables')

for i in cur:
print(i)

Output:

32 Write a program to insert value in table employee.


import mysql.connector as sql
import pandas as pd

con=sql.connect(user='root',password='root',host='localhost')
cur=con.cursor()
cur.execute('create database if not exists hps')
cur.execute('use hps')
cur.execute('create table if not exists emp(code char(4), name varchar(40), salary int)')

code=input("Enter code ")


name=input("Enter name ")
salary=input("Enter salary ")
cur.execute("insert into emp values('"+code+"','"+name+"',"+salary+")")
con.commit()

print("Record has been inserted ")

output:
33 Write a program to display all records from emp.
import mysql.connector as sql

import pandas as pd
con=sql.connect(user='root',password='root',host='localhost')
cur=con.cursor()
cur.execute('create database if not exists hps')
cur.execute('use hps')

cur.execute('select *from emp')


for i in cur:
print(i)

You might also like