PDF&Rendition 1
PDF&Rendition 1
Data Handling
1. Create a panda’s series from a dictionary of values and a ndarray.
( i ). Creating series using a dictionary:
import pandas as pd
dict = { 'January': 31, 'February': 28, 'March': 31, 'April' : 30 }
sr1 = pd.Series(dict)
print(sr1)
Output-
January 31
February 28
March 31
April 30
dtype: int64
import pandas as pd
lst1 = [1, 2, 3, 4, 5]
df = pd.DataFrame( lst1 )
print( df )
Output-
0
0 1
1 2
2 3
3 4
4 5
Output-
Name Age
0 Rohit 10
1 Mohit 12
2 Sohit 13
# Creating dataframe using series:
import pandas as pd
stu_roll = pd.Series( {'Khushi': 101, 'Anjali': 105, 'Annu' : 104, 'Kalpana' : 109, 'Gulab' : 110} )
stu_Marks = pd.Series( {'Khushi': 89, 'Anjali': 86, 'Annu' : 92, 'Kalpana' : 93, 'Gulab' : 82} )
dict = {'Roll No' : stu_roll , 'Marks' : stu_Marks }
stu_df = pd.DataFrame(dict)
print( stu_df )
Output-
Roll No Marks
Khushi 101 89
Anjali 105 86
Annu 104 92
Kalpana 109 93
Gulab 110 82
import pandas as pd
data = pd.read_csv( 'C:\\Users\\ Desktop\\Python\\StudentsDetails.csv’ )
dt = data.head()
print( dt )
# \U in "C:\Users... starts an eight-character Unicode escape, which shows
error, You either need to duplicate all backslashes.
Output-
Sr. No name board class section city
0 52 NISHANT CBSE XII A NEW DELHI
1 53 ARYA KUMAR CBSE XII A NEW DELHI
2 54 SHASHWAT CBSE XII A NEW DELHI
3 55 RANJEET YADAV CBSE XII A NEW DELHI
4 56 YASHARTH CHAUHAN CBSE XII A NEW DELHI
4. (i). Create a Data Frame using a dictionary of students name and marks of
subjects- English, IP, Accounts, Economics. Set its index as Name column. Add a
new column ‘B St’ and then ‘Total’ as sum of marks of all subjects.
import pandas as pd
# Dictionary containing students data
data = {'Name':['Ajay', 'Vijay', 'Jay', 'Sanjay', 'Pranay' ], 'Eng':[65,70, 55, 83, 90],’IP':[ 82, 94,
90, 76, 87], 'Acc':[78, 67, 82, 56,69], 'Eco':[85, 90,64, 71, 79]}
df = pd.DataFrame(data )
# To set the Name column as index:
df.set_index( 'Name', inplace = True )
print( df )
# To add a new column 'B St' to an already existing dataframe df:
df['B St'] = [65, 79, 83, 62, 69]
print(df)
# Adding column 'Total' to a dataframe:
df['Total'] = df['Eng']+ df['IP'] + df['Acc'] + df['Eco']+ df['B St']
print( df )
Output-
Eng IP Acc Eco
Name
Ajay 65 82 78 85
Vijay 70 94 67 90
Jay 55 90 82 64
Sanjay 83 76 56 71
Pranay 90 87 69 79
Eng IP Acc Eco B St
Name
Ajay 65 82 78 85 65
Vijay 70 94 67 90 79
Jay 55 90 82 64 83
Sanjay 83 76 56 71 62
Pranay 90 87 69 79 69
Eng IP Acc Eco B St Total
Name
Ajay 65 82 78 85 65 375
Vijay 70 94 67 90 79 400
Jay 55 90 82 64 83 374
Sanjay 83 76 56 71 62 348
Pranay 90 87 69 79 69 394
4 (ii). Using the dataframe created in 4(i), write code to add a new row as-
[‘Dhananjay’,87,59,73,70,84]. Use drop() method to delete rows and columns.
Use rename method to rename row and column labels. Also write code to
access data using loc and iloc functions.
# Adding a row using loc
df.loc['Dhananjay'] = [87,59,73,70,84]
print(df)
Output-
Eng IP Acc Eco B St
Name
Ajay 65 82 78 85 65
Vijay 70 94 67 90 79
Jay 55 90 82 64 83
Sanjay 83 76 56 71 62
Pranay 90 87 69 79 69
Dhananjay 87 59 73 70 84
# Use of loc
r2 = df.loc[ ['Jay','Sanjay']]
print( r2 )
Output-
Eng IP Eco
Name
Jay 55 90 64
Sanjay 83 76 71
# Use of loc
r3 = df.loc[ : , [ 'Eng', 'Eco' ] ]
print( r3 )
Output-
Eng Eco
Name
Ajay 65 85
Vijay 70 90
Jay 55 64
Sanjay 83 71
Pranay 90 79
5 . Create two dataframes df1 and df2. Create dataframes d3 and d4 by using
concat() function for concatenating df1 and df2 row wise and column wise
respectively.
import pandas as pd
# 1st dataframe
d1 = { 'roll_no' : [ 9, 10, 11, 12, 13, 14 ], 'name' : ['Akhil', 'Nikhil', 'Pooja','Rinki','Pinki', 'Chinki']
}
df1 = pd.DataFrame( d1, columns = [ 'roll_no', 'name' ])
print( df1 )
Output-
roll_no name
0 9 Akhil
1 10 Nikhil
2 11 Pooja
3 12 Rinki
4 13 Pinki
5 14 Chinki
# 2nd dataframe
d2 = { 'roll_no' : [ 1, 2, 3 ,4, 5, 6 ], 'name' : ['Akash', 'Prakash', 'Vikas', 'Ardas', 'Chhaya',
'Maya'] }
df2 = pd.DataFrame( d2, columns = ['roll_no', 'name'])
print( df2 )
Output-
roll_no name
0 1 Akash
1 2 Prakash
2 3 Vikas
3 4 Ardas
4 5 Chhaya
5 6 Maya
# concatenating row-wise
d3 = pd.concat( [df1, df2], axis = 0 )
print( d3 )
Output-
roll_no name
0 9 Akhil
1 10 Nikhil
2 11 Pooja
3 12 Rinki
4 13 Pinki
5 14 Chinki
0 1 Akash
1 2 Prakash
2 3 Vikas
3 4 Ardas
4 5 Chhaya
5 6 Maya
# concatenating column-wise
d4 = pd.concat( [df1, df2], axis = 1 )
print( d4 )
Output-
roll_no name roll_no name
0 9 Akhil 1 Akash
1 10 Nikhil 2 Prakash
2 11 Pooja 3 Vikas
3 12 Rinki 4 Ardas
4 13 Pinki 5 Chhaya
5 14 Chinki 6 Maya
6. Create two Data Frames df1 and df2 with given values. Use append() method
to join df1 and df2.
import pandas as pd
dFrame1 = pd.DataFrame( [ [1, 2, 3], [4, 5], [6] ], columns = ['C1', 'C2', 'C3'],
index = ['R1', 'R2', 'R3'] )
dFrame2 = pd.DataFrame( [ [10, 20], [30], [40, 50]], columns = ['C2', 'C5'],
index = ['R4', 'R2', 'R5'] )
print(dFrame1)
C1 C2 C3
R1 1 2.0 3.0
R2 4 5.0 NaN
R3 6 NaN NaN
print(dFrame2)
C2 C5
R4 10 20.0
R2 30 NaN
R5 40 50.0
# Joinig two dataframes using append() method
dFrame1 = dFrame1.append(dFrame2)
print(dFrame1)
C1 C2 C3 C5
R1 1.0 2.0 3.0 NaN
R2 4.0 5.0 NaN NaN
R3 6.0 NaN NaN NaN
R4 NaN 10.0 NaN 20.0
R2 NaN 30.0 NaN NaN
R5 NaN 40.0 NaN 50.0
7. Create a Data Frame book with columns SNo, BName, Auth, Pages, Pr. Export
the data from this dataframe to –
(i) create a new CSV file books.csv at a specified location in your computer.
(ii) append the data from dataframe book to an existing CSV file namely
BooksNBT.csv at an specified location in your computer.
# Export data to CSV –
import pandas as pd
# list of data
SNo = [ 13, 14]
BName = [ "INDIAN RAILWAYS", "INDUSTRIAL DEVELOPMENT" ]
Auth = [ "M A Rao" , "M R Kulkarni"]
Pages =[ 356, 544 ]
Pr = [ 175, 360]
# dictionary of lists
dict = {'S_No': SNo, 'Book_Name': BName, 'Author': Auth, 'No_Pages': Pages, 'Price' : Pr }
book = pd.DataFrame(dict)
(i) # saving the dataframe to a new CSV file Books.csv
df.to_csv(r"C:\Users\Admin\Desktop\Python\Books.csv", index = False)
(ii)
# saving the data to an existing file BooksNBT.csv at the end of existing data.
df.to_csv( r"C:\Users\Admin\Desktop\Python\BooksNBT.csv", mode = 'a', header = False,
index = False )
# mode = ‘a ‘means append the new data at the end of existing data.
# By default mode is ‘w’ means overwrite existing records.
#header = False means headings of columns will not be printed.
# If True headings will be printed between existing and new data.
8. Create a Data Frame quarterly sales where each row contains the item
category, item name, and expenditure. Group the rows by the category and
print the total expenditure per category.
import pandas as pd
dictqs = { 'Item Category' : ['Grocery','Stationery','Grocery','Stationery','Fruits',
'Grocery','Fruits', 'Grocery', 'Fruits','Stationery', 'Fruits'],
'Item Name' : ['Milk', 'Pen', 'Rice', 'Notebook', 'Mangoes', 'Wheat Flour', 'Banana', 'Oil',
'Apples', 'Feviquick', 'Orange']
'Expenditure': [ 16500, 880,13600, 2700, 5600, 11200, 3800, 12800, 7400, 1240, 8300 ] }
------------Stationery Items--------------
Item Category Item Name Expenditure
1 Stationery Pen 880
3 Stationery Notebook 2700
9 Stationery Feviquick 1240
------------Fruit Items--------------
Item Category Item Name Expenditure
4 Fruits Mangoes 5600
6 Fruits Banana 3800
8 Fruits Apples 7400
10 Fruits Orange 8300
import numpy as np
x = np.arange(1, 11)
y1 = 2 * x + 3
y2 = 7 * x - 4
plt.legend()
plt.show()
10. Write a python program to create line chart for Sine function. The values of
x are to taken from an numpy array between -2 to 1 at an interval of 0.01.
import numpy as np
plt.xlabel( "Values" )
plt.ylabel("Sine of values")
plt.show()
11. Write a python program to create a bar chart to show comparison of
popularity of programming languages. Use the given below lists to create bars:
prog_lang = ['Python', 'Java', 'Javascript', 'C#', 'PHP', 'C/C++', 'R']
import numpy as np
plt.xlabel('Use Percent')
plt.show()
12. Write a python program to create a bar chart showing comparison between
the sales of different car brands in December-2018 and December-2019. The
data is given below:
Brand = ['Maruti', 'Hyundai', 'Mahindra', 'Tata', 'Renault', 'Honda', 'Toyota']
import numpy as np
width = 0.5
plt.xticks( x, Brand )
plt.legend()
plt.show()
13. Write a python program to create a histogram by generating an array of
1000 random values. Take bin value as 25. Choose Colour of histogram as
yellow and edge colour as blue.
import numpy as np
y = np.random.randn( 1000 )
plt.xlabel('X- Axis')
plt.show()
# bin value is 25
# Edgecolour is blue
14. Write a python program to create a histogram from the given list of marks
of students. Also use savefig() method to save the image in python folder of
your computer. Take bin values with difference of 50 marks. The values are:
T_marks = [ 250, 355, 467, 167, 180, 345, 278, 478,267, 298,
345,367,387,333,324,318,435, 467,436, 456, 256, 279, 345, 381, 324,312,339,
450,470, 134, 123, 194, 199 ,245, 412]
T_marks = [ 250, 355, 467, 167, 180, 345, 278, 478,267, 298,
345,367,387,333,324,318,435, 467,436, 456, 256, 279, 345, 381, 324,312,339,
450,470, 134, 123, 194, 199 ,245, 412]
bins = [ 0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500 ]
plt.xlabel('Total Marks')
plt.legend()
plt.savefig(“Totalmarks.png”)
plt.show()
15. Write a python program to create a dataframe namely ‘df’ using the
dictionary containing roll no, marks of English and marks of IP.
dict = { 'Roll No':[ 1, 2, 3, 4, 5, 6, 7, 8 ], 'Eng':[91,67,89,56,78,84,72,63],
'IP':[95,86,72,93,69,64,82,92]}
Now Create a line chart to show the comparison of marks of English and IP using
the dataframe ‘df’.
import pandas as pd
df =pd.DataFrame( dict )
print( df )
ax = plt.gca()
# gca() stands for get current axis. It is used to display two plots with same axis.
plt.show()
Output-
Roll No Eng IP
0 1 91 95
1 2 67 86
2 3 89 72
3 4 56 93
4 5 78 69
5 6 84 64
6 7 72 82
7 8 63 92
import pandas as pd
import matplotlib.pyplot as plt
MelaSalesdf = pd.read_csv(r'C:\Users\Sunil Dutt\Desktop\MelaSales.csv')
print(MelaSalesdf)
# plots a bar chart with the column "Days" as x axis
MelaSalesdf.plot( kind = 'bar', x ='Day', color = ['r','y','m'], edgecolor = 'blue')
plt.title('Mela Sales Comparision')
plt.xlabel('Days')
plt.ylabel('Sales in Rs.')
plt.show()
Ques-9
Ques-10
Ques-11
Ques-12
Ques-13
Ques-14
Ques-15
Ques-16
Practical Class - XII
PART - II
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| school |
| sys |
| world |
| xiiab |
| xiikn |
+--------------------+
Database changed
+----------------------+
| Tables_in_xiiabfinal |
+----------------------+
| student |
+----------------------+
1 row in set (1.84 sec)
+---------+---------------------------------------------------------------------------------------------- +
+---------+----------------------------------------------------------------------------------------------+
+---------+----------------------------------------------------------------------------------------------+
Query OK
+-------+--------+-----------+-------------+------------+-------+------------+------------+
+-------+--------+-----------+-------------+------------+-------+------------+------------+
| 101 | VISHNU | SATYA PAL | SUNITA DEVI | 2010-01-07 | XII A | NEW DELHI |
9876543210 |
+-------+--------+-----------+-------------+------------+-------+------------+------------+
+-------+--------+-------+
+-------+--------+-------+
| 104 | AMAR | XI C |
+-------+--------+-------+
+-----------+
| ADDRESS |
+-----------+
| NEW DELHI |
| DELHI |
| NULL |
+-----------+
15. # USE OF LIKE KEYWORD WITH '%' SYMBOL FOR PATTERN MATCH
mysql> SELECT SNAME, DOB FROM STUDENT WHERE SNAME LIKE 'A%';
+-------+------------+
| SNAME | DOB |
+-------+------------+
| AMIT | 2011-05-07 |
| AMAR | 2009-05-25 |
+-------+------------+
+--------+------------+
| SNAME | DOB |
+--------+------------+
| VISHNU | 2010-01-07 |
| AMIT | 2011-05-07 |
+--------+------------+
16. # USE OF LIKE KEYWORD WITH '_' SYMBOL FOR PATTERN MATCH
mysql> SELECT SNAME, CLASS FROM STUDENT WHERE SNAME LIKE '_M%';
+-------+-------+
| SNAME | CLASS |
+-------+-------+
| AMIT | XII B |
| AMAR | XI C |
+-------+-------+
mysql> SELECT SNAME, CLASS FROM STUDENT WHERE SNAME LIKE '_ _M%';
+--------+-------+
| SNAME | CLASS |
+--------+-------+
| RAMESH | XI A |
+--------+-------+
mysql> SELECT SNAME, CLASS, DOB FROM STUDENT WHERE DOB BETWEEN
'2010-01-07' AND '2011-12-31';
+--------+-------+------------+
+--------+-------+------------+
+--------+-------+------------+
mysql> SELECT SNAME, CLASS FROM STUDENT WHERE CLASS IN ('XII A','XI C');
+--------+-------+
| SNAME | CLASS |
+--------+-------+
| VISHNU | XII A |
| AMAR | XI C |
+--------+-------+
+--------+-------+
| SNAME | CLASS |
+--------+-------+
| VISHNU | XII A |
| AMAR | XI C |
+--------+-------+
mysql> SELECT SNAME, CLASS FROM STUDENT WHERE CLASS NOT IN ('XII A','XI
C');
+--------+-------+
| SNAME | CLASS |
+--------+-------+
| AMIT | XII B |
| RAMESH | XI A |
+--------+-------+
mysql> SELECT SNAME, CLASS FROM STUDENT WHERE CLASS = 'XII A' AND
ADDRESS = 'NEW DELHI';
+--------+-------+
| SNAME | CLASS |
+--------+-------+
| VISHNU | XII A |
+--------+-------+
mysql> CREATE TABLE EMPL( ECODE INT PRIMARY KEY, ENAME VARCHAR(20)
NOT NULL , JOB VARCHAR(15) DEFAULT ‘MTS’ , SALARY INT(6) CHECK ( SALARY >
10000 ), DEPT VARCHAR(15), MOBILE BIGINT UNIQUE );
+--------+----------+
| ENAME | DEPT |
+--------+----------+
| SUNIL | SALES |
| RAMAN | SALES |
| CHAMAN | SALES |
| ANIL | PURCHASE |
| AMAN | PURCHASE |
+--------+----------+
+--------+----------+
| ENAME | DEPT |
+--------+----------+
| AMAN | PURCHASE |
| ANIL | PURCHASE |
| CHAMAN | SALES |
| RAMAN | SALES |
| SUNIL | SALES |
+--------+----------+
5 rows in set (0.00 sec)
+-------+--------+---------+--------+----------+------------+
+-------+--------+---------+--------+----------+------------+
+-------+--------+---------+--------+----------+------------+
+------------+----------+
| COUNT(JOB) | DEPT |
+------------+----------+
| 3 | SALES |
| 2 | PURCHASE |
+------------+----------+
mysql> SELECT AVG(SALARY), DEPT FROM EMPL GROUP BY DEPT HAVING DEPT =
'SALES';
+-------------+-------+
| AVG(SALARY) | DEPT |
+-------------+-------+
| 16333.3333 | SALES |
+-------------+-------+
+-------------+-------------+-------------+
+-------------+-------------+-------------+
+-------------+-------------+-------------+
mysql> SELECT CONCAT(ENAME, SALARY) FROM EMPL WHERE SALARY >= 12000;
+-----------------------+
| CONCAT(ENAME, SALARY) |
+-----------------------+
| SUNIL25000 |
| ANIL15000 |
| AMAN18000 |
| RAMAN13000 |
+-----------------------+
+---------------------+------------+
| SUBSTR(ENAME, 1, 3) | MOBILE |
+---------------------+------------+
| SUN | 9812312312 |
| ANI | 9812312333 |
| AMA | 9812310233 |
| RAM | 9816710233 |
| CHA | 9656710233 |
+---------------------+------------+
+--------------------+--------+
+--------------------+--------+
| 0 | SUNIL |
| 1 | ANIL |
| 3 | AMAN |
| 4 | RAMAN |
| 5 | CHAMAN |
+--------------------+--------+
+-------------------------------+
| UPPER("Informatics Pracices") |
+-------------------------------+
| INFORMATICS PRACICES |
+-------------------------------+
32 # USE OF SINGLE ROW FUNCTION- LCASE() / LOWER()
+--------------------------+
| LCASE("SWACHCHH BHARAT") |
+--------------------------+
| swachchh bharat |
+--------------------------+
+--------------------------+
| LENGTH("INDIA IS GREAT") |
+--------------------------+
| 14 |
+--------------------------+
+---------------------+
| LEFT("GREATEST", 3) |
+---------------------+
| GRE |
+---------------------+
35 # USE OF SINGLE ROW FUNCTION- RIGHT()
+----------------------+
| RIGHT("GREATEST", 4) |
+----------------------+
| TEST |
+----------------------+
+--------------------+----------------------------+--------------------------+-------------------------+
| LENGTH(" DELHI ") | LENGTH(LTRIM(" DELHI ")) | LENGTH(RTRIM(" DELHI ")) | LENGTH(TRIM(" DELHI ")) |
+--------------------+----------------------------+--------------------------+-------------------------+
| 9 | 7 | 7 | 5 |
+--------------------+---------------------------+---------------------------+-------------------------+
+-------------+
| POWER(3, 2) |
+-------------+
| 9 |
+-------------+
38 # USE OF SINGLE ROW FUNCTION- ROUND()
mysql> SELECT ROUND(9872.38),ROUND(9872.38, 1), ROUND(9872.38, -1),ROUND(9872.38, -2);
+------------------------+---------------------------+-----------------------------+----------------------------+
+------------------------+----------------------------+-----------------------------+----------------------------+
+------------------------+-----------------------------+-----------------------------+----------------------------+
+-----------------+
| MOD(20, 3) |
+------------------+
| 2 |
+------------------+
+----------------------------+
| NOW() |
+-----------------------------+
| 2022-11-19 21:00:04 |
+-----------------------------+
41 # USE OF SINGLE ROW FUNCTION- DATE()
+--------------------+
| DATE(NOW()) |
+--------------------+
| 2022-11-19 |
+--------------------+
+-----------------------------+-------------------------+------------------------+--------------------------------+
+-----------------------------+--------------------------+------------------------+--------------------------------+
| 12 | 2022 | 20 | Tuesday |
+------------------------------+--------------------------+------------------------+--------------------------------+
Query OK
Query OK