0% found this document useful (0 votes)
3 views32 pages

Unit4 - Python QN Bank Solved

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
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)
3 views32 pages

Unit4 - Python QN Bank Solved

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
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

UNIT IV

Python SQLite, Data analysis and Data Visualization


1. How do you connect to the SQLite database? Give example.
We can connect to SQLite database in Python, first we have to import the sqlite3 module and then create a connection
object. Connection object allows to connect to the database and will let us execute the SQL statements. To create
Connection object use the connect() function:
Example:
import sqlite3
con = [Link]('[Link]')
This will create a new file with the name ‘[Link]’.
2. Write the syntax to create cursor objects in SQLite. Give example.
To execute SQLite statements in Python, we need a cursor object. We can create it using the cursor() method. Create an
object of the cursor using the connection object as follows:
Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
We can use the cursor object to call the execute() method to execute any SQL queries.
3. How is table created in SQLite database? Give example.
To create a table in SQLite3, you can use the Create Table query in the execute() method.
Consider the following steps:
1. Create a connection object.
2. From the connection object, create a cursor object.
3. Using the cursor object, call the execute method with create table query as the parameter.
Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
[Link]('''CREATE TABLE student(name text, year int, score real)''')
[Link]()
[Link]()
The commit() method used in the above example saves all the changes we make.
4. Write SQL code to insert data in SQLite table.
To insert data in a table, we use the INSERT INTO statement.
Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
[Link]('''CREATE TABLE student(name text, year int, score real)''')
[Link]('''INSERT INTO student VALUES ("Ashwini",1997, 9.5)''')
[Link]()
[Link]()
We can also pass values to an INSERT statement in the execute() method. You can use the question mark (?) as a
placeholder for each value.
Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
m=input("Movie Name :")
y=int(input("Year :"))
s=float(input("Score :"))
[Link]('''INSERT INTO MOVIE VALUES (?,?,?) ''',(m,y,s))
[Link]()
[Link]()

5. Write SQL code to update SQLite table.


To update the table, simply create a connection, then create a cursor object using the connection and finally use the
UPDATE statement in the execute() method. Suppose that we want to update the score with the student rollno 101. For
updating, we will use the UPDATE statement and for the student whose rollno equals 101. We will use the WHERE clause
as a condition to select this employee.
Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
[Link]("UPDATE STUDENT SET SCORE=90 WHERE rollno=101 ")
[Link]()
[Link]()
This will change the score for the student with rollno 101 to 90.
6. What is NumPy in Python? Give any two uses of NumPy.
Numpy short for Numerical Python, is the foundational open-source library for scientific computing and numerical
analysis in the Python programming language. It is primarily used for handling large, multi-dimensional arrays and
matrices, offering significantly faster performance than standard Python lists.
Two Common Uses:
• Machine Learning and AI (Data Handling)
• Data Analysis and Statistics
7. Write the syntax to create NumPy array using array function. Give an example.

You can create a NumPy array from a regular Python list or tuple using the [Link]() function. The type of the resulting
array is known from the type of the elements.
Example1:

import numpy as np
a = [Link]([1,2,3,4]) #integer array

Example2:

import numpy as np
b = [Link]([9.1,8.2,7.3,4.6]) #floating point array

Example3:
import numpy as np
c= [Link]([[1,2,3],[4,5,6]]) #two – dimensional array creation using list

Example4:
import numpy as np
d= [Link]((1,2,3),(4,5,6)) #two – dimensional array creation using tuple
8. Write the syntax to create Numpy array using linspace function .Give example.
Syntax:
[Link](start,stop,num=50,dtype=none)
Start – start is the starting value of the sequence
Stop – stop is the end value of the sequence
Num – (an integer and optional) is the number of samples to generate. Default is 50. Must be non – negative.
Dtype – optional. Type of the output array.
9. How to create two-dimensional arrays using NumPy.
You can create a NumPy array from a regular Python list or tuple using the [Link]() function. The type of the resulting
array is known from the type of the elements.

Example1:
import numpy as np
c= [Link]([[1,2,3],[4,5,6]]) #two – dimensional array creation using list

Example2:
import numpy as np
d= [Link]((1,2,3),(4,5,6)) #two – dimensional array creation using tuple
10. What is the purpose of arange() in Numpy . Give example.
The arrange() returns evenly spaced values within a given interval.
Ex:
[Link](10, 30, 5)
output: array([10, 15, 20, 25])
In the above example, starting value is 10 and end value is 30, interval value is 5. Hence the array is populated with values
starting from 10 up to 30 with 5 interval.
11. List any four NumPy array attributes.

12. What is Pandas Library ?


Pandas library is a powerful, open-source Python library designed for data manipulation and analysis. It is widely
considered the industry standard for working with structured (tabular) data, like how you would use a spreadsheet or SQL
table. Pandas is a Python library that provides fast, flexible, and expressive data structures designed to make working with
“relational” or “labeled” data both easy and intuitive.

13. What is Padas Series ? Give example.


Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers,
Python objects, etc.). The axis labels are collectively referred to as the index. Pandas Series is created using series() method
and its syntax is,
s = [Link](data, index=None)
Here, s is the Pandas Series, data can be a Python dict, a ndarray, or a scalar value (like 5). The passed index is a list of
axis [Link] integer and label-based indexing are supported. If the index is not provided, then the index will default to
range(n) where n is the length of data.

import numpy as np
import pandas as pd
s = [Link]([Link](5), index=['a', 'b', 'c', 'd', 'e’])
14. How to create Dataframe from a dictionary and display its contents ?
It is possible to create a Python dictionary that contains employee data. Dictionary stores data in the form of key-value
pairs. We take ‘empid’, ‘ename’, ‘sal’, ‘doj’, as keys and corresponding lists as values. Create a dictionary by the name
‘empdata’.
Ex:

import pandas as pd

# 1. Define your dictionary


data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']
}

# 2. Create the DataFrame


df = [Link](data)

# 3. Display the contents


print(df)
15. How to create Dataframe from a tuple and display its contents ?

import pandas as pd

# 1. Create a tuple containing inner tuples (rows)


data = (
('Alice', 25, 'New York'),
('Bob', 30, 'London'),
('Charlie', 35, 'Paris')
)

# 2. Convert to DataFrame and specify column names


df = [Link](data, columns=['Name', 'Age', 'City'])

# 3. Display contents
print(df)
16. What is Pandas DataFame ? How is it created ?
Data frame is an object that is useful in representing data in the form of rows and columns. We can represent the data in
the form of a data frame. Once the data is stored into the data frame, we can perform various operations that are useful in
analyzing and understanding the data. Data frames are generally created from .csv (comma separated values) files, Excel
spreadsheet files, Python dictionaries, list of tuples or list of dictionaries.
17. What is the purpose of Head and Tail method in DataFrame?
The Head and Tail method in DataFrame is used to retrieve rows from data frame. The method head() gives the first 5
rows and the method tail() returns the last 5 rows. To display only the first 2 rows, we can use head() method by passing
2 to it. Similarly, to display the last 2 rows, we can use tail(2).
18. How create dataframe from .csv / excel file?
• To read the data from Excel file, we should use read_excel() function of pandas package in the following format:
read_excel(‘file path’, ‘sheet number’)
• We can read data from a .csv file using read_csv() function
19. How to add new column to dataframe ?
The most common ways to add a new column to a Pandas DataFrame in Python are direct assignment.
The simplest way is to treat the DataFrame like a dictionary. This adds the column to the end of the DataFrame.
import pandas as pd

# Adding a column with a single constant value


df['new_column'] = 10

# Adding a column from a list (must match the length of the DataFrame)
df['new_column'] = [1, 2, 3, 4]
20. Give Python code to find maximum and minimum values for column of dataframe.
df[sal].max()
df[sal].min()
21. What is Data Visualization ? List the different types of charts created.
When data is shown in the form of pictures, it becomes easy for the user to understand it. Representing data in the form
of pictures or graphs is called ‘data visualization’.
The different types of charts:
• Bar graph
• Histogram
• Pie chart
• Line graph
22. What is matplotlib and pyplot ?
matplotlib is a comprehensive library in Python primarily used for creating static, animated, and interactive visualizations.
Matplotlib supports various types of plots, including line plots, bar charts, scatter plots, histograms, pie charts, and more.
Within the matplotlib library, pyplot is a module that provides a collection of functions that make it easier to create
various kinds of plots.
Pyplot provides a set of functions for creating and customizing plots with a minimal amount of code. Simplifies the
process of creating basic plots by providing functions like plot(), scatter(), bar(), hist(), pie(), etc.

Long answer Questions


1. Explain four SQLite module methods required to use SQLite database.
SQLite Methods
1. connect():
▪ To use SQLite3 in Python, first we have to import the sqlite3 module and then create a connection object.
▪ Connection object allows to connect to the database and will let us execute the SQL statements.
▪ Creating Connection object using the connect() function:
▪ Example:
import sqlite3
con = [Link]('[Link]')
▪ This will create a new file with the name ‘[Link]’.
2. cursor():
▪ To execute SQLite statements in Python, we need a cursor object.
▪ We can create it using the cursor() method.
▪ Create an object of the cursor using the connection object as follows:
▪ Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
▪ We can use the cursor object to call the execute() method to execute any SQL queries.
3. execute():
▪ Once the database and connection object is created, we can create a table using CREATE TABLE statement.
▪ Then we execute the CREATE TABLE statement by calling [Link](...).
▪ Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
[Link](''' CREATE TABLE movie(title text, year int, score real) ''' )
▪ Here, ‘movie’ is the table name with columns title, year and score.
▪ Since SQLite is flexible, we can just use column names in the table declaration, specifying the data types is
optional.
4. close():
▪ Once we are done with our database, it is a good practice to close the connection.
▪ We can close the connection by using the close() method.
▪ To close a connection, use the connection object and call the close() method as follows:
▪ Example:
con = [Link]('[Link]')
#program statements
[Link]()
2. Explain any four SQLite database operations with example.
1. Creating and connecting to Database:
When you create a connection with SQLite, that will create a database file automatically if it doesn’t already exist. This
database file is created on disk with the connect function. Following Python code shows how to connect to an existing
database. If the database does not exist, then it will be created and finally a database object will be returned.
Example:
import sqlite3
conn = [Link]('[Link]')
print("Opened database successfully")
2. Create Table:
To create a table in SQLite3, you can use the Create Table query in the execute() method.
Consider the following steps:
1. Create a connection object.
2. From the connection object, create a cursor object.
3. Using the cursor object, call the execute method with create table query as the parameter.
Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
[Link]('''CREATE TABLE student(name text, rollno int, percentage real)''')
[Link]()
[Link]()
The commit() method used in the above example saves all the changes we make.
3. Insert into Table:
To insert data in a table, we use the INSERT INTO statement.
Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
[Link]('''CREATE TABLE student(name text, rollno int, percentage real)''')
[Link]('''INSERT INTO student VALUES ("Nishmita",1001, 95.5)''')
[Link]()
[Link]()
You can use the question mark (?) as a placeholder for each value.
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
m=input("Student Name :")
y=int(input("Roll number :"))
s=float(input("Percentage :"))
[Link]('''INSERT INTO Student VALUES (?,?,?) ''',(m,y,s))
[Link]()
[Link]()
4. Update Table:
To update the table, simply create a connection, then create a cursor object using the connection and finally use the
UPDATE statement in the execute() method. Suppose that we want to update the score with the movie title Dil. For
updating, we will use the UPDATE statement and for the movie whose title equals Dil. We will use the WHERE clause as
a condition to select this employee.
Example:
import sqlite3
con = [Link]('[Link]')
cursorObj = [Link]()
[Link]("UPDATE STUDENT SET PERCENTAGE=85.6 WHERE ROLLNO=1001 ")
[Link]()
[Link]()
This will change the percentage for the student with rollno 1001 to 85.6
3. Write a Python Program to demonstrate various SQLite Database operations.
#importing the module
import sqlite3
#create connection object
con = [Link]('[Link]')

#crete a cursor
cursorObj = [Link]()

#creating the table


[Link]('''CREATE TABLE student(name text, rollno int, percentage real)''')

#inserting the data


[Link]('''INSERT INTO student VALUES ("Ashwini",1001, 93.5)''')
[Link]('''INSERT INTO student VALUES ("Harshita",1002, 92.1)''')
[Link]('''INSERT INTO student VALUES ("Vaishnavi",1003, 88.5)''')

#Print the Initial Data


print("Initial Data...")
[Link]("SELECT * FROM student ")
[print(row) for row in [Link]()]
#Updating
[Link]("UPDATE STUDENT SET PERCENTAGE=70 WHERE NAME='Ashwini' ")
#Print the after updating
print("After updating...")
[Link]("SELECT * FROM STUDENT ")
[print(row) for row in [Link]()]

#Deleting
[Link]("Delete from STUDENT where name='Vaishnavi' ")

#Print the after Deleting


print("After deleting...")
[Link]("SELECT * FROM STUDENT ")
[print(row) for row in [Link]()]
#Drop the table
[Link](" DROP TABLE IF EXISTS STUDENT ")
#commit changes in the database
[Link]()
#close the connection
[Link]()
4. Explain any five NumPy array attributes with syntax.

5. Explain any five NumPy array creation functions with example.


Ex:
>>> import numpy as np
>>> [Link]((2,3))
array([[0., 0., 0.],
[0., 0., 0.]])
The 2 rows and 3 columns of the array is filled with 0’s
>>> [Link]((3,4))
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
The 3 rows and 4 columns of the array is filled with 1’s

>>> [Link]((2,3))
array([[0., 0., 0.],
[0., 0., 0.]])
The array is represented empty with values 0.

>>> [Link]((3,3),2)
array([[2, 2, 2],
[2, 2, 2],
[2, 2, 2]])
The 3 rows and 3 columns of the array is filled with the value 2
>>> [Link](2,2)
array([[1., 0.],
[0., 1.]])
The eye function created 2*2 identity matrix
>>> [Link]((2,2))
array([[0.95022839, 0.23253555],
[0.843828 , 0.57976282]])
2*2 array of random values is generated
>>> [Link](10, 30, 5)
array([10, 15, 20, 25])
In the above example, starting value is 10 and end value is 30, interval value is 5. Hence the array is populated with values
starting from 10 up to 30 with 5 intervals.

>>> [Link](0, 2, 0.3)


array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
the arrange() produces floating point elements up to 2.
>>> [Link](0, 2, 9)
array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
the linspace() function produces nine data elements between zero and two.

6. Explain the following NumPy array creation function with example:


i) linspace ii)arrange() iii) zeros and ones iv) empty and full

Refer question number 5.


7. Write a note on Indexing, slicing, and iterating operations on NumPy array.
NumPy arrays support various operations such as Indexing, Slicing, and Iterating. These operations help in
accessing, retrieving, and processing array elements efficiently.
1. Indexing in NumPy Array
Indexing is used to access individual elements of a NumPy array. Array indexing starts from 0. Both one-
dimensional and multi-dimensional arrays can be indexed.
Syntax
array_name[index]
For a 2-D array:
array_name[row][column]
Example 1: Indexing in 1-D Array
import numpy as np

a = [Link]([10, 20, 30, 40])

print(a[0])
print(a[2])
Output
10
30
Explanation:
• a[0] accesses the first element.
• a[2] accesses the third element.
Example 2: Indexing in 2-D Array
import numpy as np

a = [Link]([[1, 2],
[3, 4]])

print(a[0][1])
Output
2
Explanation:
• a[0][1] accesses the element in the first row and second column.

2. Slicing in NumPy Array


Definition
Slicing is used to access a group of elements from an array. It allows us to retrieve a specific portion of an array.
Syntax
array_name[start : stop : step]
Where:
• start → starting index
• stop → ending index (excluded)
• step → interval between elements
Example 1: Basic Slicing
import numpy as np

a = [Link]([10, 20, 30, 40, 50])

print(a[1:4])
Output
[20 30 40]
Explanation:
• Starts from index 1.
• Stops before index 4.
Example 2: Slicing with Step Value
import numpy as np

a = [Link]([10, 20, 30, 40, 50, 60])

print(a[0:6:2])
Output
[10 30 50]
Explanation:
• Retrieves every second element from index 0 to 5.
Slicing in 2-D Arrays
import numpy as np

a = [Link]([[1,2,3],
[4,5,6],
[7,8,9]])

print(a[0:2,1:3])
Output
[[2 3]
[5 6]]
Explanation:
• Selects first two rows and columns from index 1 to 2.

3. Iterating NumPy Array


Definition
Iteration means accessing array elements one by one using loops. NumPy arrays can be traversed using for loops.
For multi-dimensional arrays, iteration can be done row-wise or element-wise.
Syntax
for variable in array_name:
statements
Example 1: Iterating a 1-D Array
import numpy as np

a = [Link]([10, 20, 30, 40])

for i in a:
print(i)
Output
10
20
30
40
Explanation:
• Each element is accessed one after another.
Example 2: Iterating a 2-D Array
import numpy as np

a = [Link]([[1, 2],
[3, 4]])

for row in a:
print(row)
Output
[1 2]
[3 4]
Explanation:
• Iteration is performed row by row.
Example 3: Iterating All Elements Using flat
import numpy as np

a = [Link]([[1,2],
[3,4]])
for x in [Link]:
print(x)
Output
1
2
3
4
Explanation:
• flat is an iterator that accesses every element of the array one by one.

8. Explain basic arithmetic operations on NumPy array with examples.


NumPy provides various arithmetic operations that can be performed directly on arrays. These operations are carried out
element-by-element, making numerical computations fast and efficient. The basic arithmetic operations are:
1. Addition
2. Subtraction
3. Multiplication
4. Division

1. Addition of Arrays
Definition
In addition, the corresponding elements of two arrays are added together.
Example
import numpy as np

a = [Link]([10, 20, 30])


b = [Link]([1, 2, 3])

c=a+b

print(c)
Output
[11 22 33]
Explanation
• 10 + 1 = 11
• 20 + 2 = 22
• 30 + 3 = 33
Thus, the resulting array is [11 22 33].

2. Subtraction of Arrays
Definition
In subtraction, corresponding elements of one array are subtracted from another.
Example
import numpy as np

a = [Link]([10, 20, 30])


b = [Link]([1, 2, 3])

c=a-b

print(c)
Output
[ 9 18 27]
Explanation
• 10 − 1 = 9
• 20 − 2 = 18
• 30 − 3 = 27
The resulting array is [9 18 27].

3. Multiplication of Arrays
Definition
In multiplication, corresponding elements of two arrays are multiplied.
Example
import numpy as np

a = [Link]([10, 20, 30])


b = [Link]([1, 2, 3])

c=a*b

print(c)
Output
[10 40 90]
Explanation
• 10 × 1 = 10
• 20 × 2 = 40
• 30 × 3 = 90
The resulting array is [10 40 90].

4. Division of Arrays
Definition
In division, corresponding elements of one array are divided by the elements of another array.
Example
import numpy as np

a = [Link]([10, 20, 30])


b = [Link]([1, 2, 3])

c=a/b

print(c)
Output
[10. 10. 10.]
Explanation
• 10 ÷ 1 = 10
• 20 ÷ 2 = 10
• 30 ÷ 3 = 10
NumPy division returns floating-point values, hence the output contains decimal points.
9. With example, explain creating pandas series using Scalar data and Dictionary.
A Pandas Series is a one-dimensional labeled array capable of storing different types of data such as integers, floats,
strings, and objects. A Series can be created using scalar data or a dictionary.
1. Creating Series using Scalar Data
Definition
A scalar is a single value. When a scalar value is used, the same value is repeated for all specified index positions.
Syntax
[Link](scalar_value, index=index_values)
Example
import pandas as pd

s = [Link](5, index=[0,1,2,3])

print(s)
Output
0 5
1 5
2 5
3 5
dtype: int64
Explanation
The scalar value 5 is assigned to all index positions (0, 1, 2, 3).

2. Creating Series using Dictionary


Definition
A Pandas Series can be created from a Python dictionary. The keys become index labels and the values become
Series data.
Syntax
[Link](dictionary_name)
Example
import pandas as pd

data = {'a':10, 'b':20, 'c':30}

s = [Link](data)
print(s)
Output
a 10
b 20
c 30
dtype: int64
Explanation
Here, a, b, c become index labels and 10, 20, 30 become the corresponding values in the Series.

Pandas Series can be created using scalar data and dictionary data. Scalar data repeats the same value for all
indexes, while dictionary data uses keys as indexes and values as Series elements. These methods provide an easy
way to organize and manage data in Pandas.

10. Explain Series indexing and slicing with example.


A Pandas Series is a one-dimensional labeled array. The elements of a Series can be accessed using indexing and
slicing operations. Indexing is used to access individual elements, whereas slicing is used to access a group of elements.
Both integer-based and label-based indexing are supported in Pandas Series.
1. Series Indexing
Definition
Indexing is the process of accessing a particular element from a Series using its index position or label.
Example
import pandas as pd

s = [Link]([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])

print(s['b'])
print(s['d'])
Output
20
40
Explanation
• s['b'] retrieves the value 20.
• s['d'] retrieves the value 40.
• Here, the labels a, b, c, d act as indexes.
Integer Indexing Example
import pandas as pd

s = [Link]([10, 20, 30, 40])

print(s[0])
print(s[2])
Output
10
30
• s[0] returns the first element.
• s[2] returns the third element.

2. Series Slicing
Definition
Slicing is used to retrieve a subset of elements from a Series.
Syntax
Series[start : stop]
• start → Starting index
• stop → Ending index (excluded)
Example
import pandas as pd

s = [Link]([10, 20, 30, 40, 50])

print(s[1:4])
Output
1 20
2 30
3 40
dtype: int64
Explanation
• Slicing starts from index 1.
• Stops before index 4.
• Returns values 20, 30, and 40.

Slicing with Labels


Example
import pandas as pd

s = [Link]([10,20,30,40], index=['a','b','c','d'])

print(s['a':'c'])
Output
a 10
b 20
c 30
dtype: int64
Explanation
• Retrieves elements from label a to c.
• In label-based slicing, the ending label is included.
11. Explain any five string processing methods supported by Pandas Library with example.
Pandas Series supports several string processing methods through the str attribute. These methods make it easy to
perform operations on each string element in a Series.
1. [Link]() Method
Definition
The lower() method converts all characters in a string to lowercase.
Example
import pandas as pd

s = [Link](['HELLO', 'WORLD'])

print([Link]())
Output
0 hello
1 world
dtype: object
Explanation
All uppercase letters are converted into lowercase letters.

2. [Link]() Method
Definition
The upper() method converts all characters in a string to uppercase.
Example
import pandas as pd

s = [Link](['hello', 'world'])

print([Link]())
Output
0 HELLO
1 WORLD
dtype: object
Explanation
All lowercase letters are converted into uppercase letters.

3. [Link]() Method
Definition
The len() method returns the length of each string.
Example
import pandas as pd
s = [Link](['Python', 'Pandas'])

print([Link]())
Output
0 6
1 6
dtype: int64
Explanation
It counts the number of characters present in each string.

4. [Link]() Method
Definition
The replace() method replaces a specified string with another string.
Example
import pandas as pd

s = [Link](['Data Mining', 'Data Science'])

print([Link]('Data', 'Big Data'))


Output
0 Big Data Mining
1 Big Data Science
dtype: object
Explanation
The word "Data" is replaced with "Big Data" in every element.

5. [Link]() Method
Definition
The contains() method checks whether a specified pattern exists in a string and returns True or False.
Example
import pandas as pd

s = [Link](['Python', 'Java', 'Python Programming'])

print([Link]('Python'))
Output
0 True
1 False
2 True
dtype: bool
Explanation
It checks whether the word "Python" is present in each string.
import pandas as pd

s = [Link](['Python', 'DATA Mining', 'Pandas Library'])

print("Original Series:")
print(s)

print("\nLower Case:")
print([Link]())

print("\nUpper Case:")
print([Link]())

print("\nLength of Strings:")
print([Link]())

print("\nReplace String:")
print([Link]('Python', 'Java'))

print("\nContains 'Data':")
print([Link]('Data', case=False))
12. Explain with example any two methods of creating DataFrame.
Creating Data Frame from an Excel Spreadsheet
Let us assume that data is present in an Excel spreadsheet file by the name ‘[Link]’. This file contains data related
to employee id number, name, salary and date of joining the company. To create the data frames, we should first import
the pandas [Link] may need xlrd package [Link] read the data from Excel file, we should use read_excel()
function of pandas package in the following format: read_excel(‘file path’, ‘sheet number’)
Open the Python IDLE window and type the commands as shown below:
We create the data frame by the name ‘df’.
Observe the first column having numbers from 0 to 5.
This column is called ‘index column’ and it is added by the data frame

import pandas as pd
import xlrd
df = pd.read_excel(“C://Users/admin/[Link]”,”sheet1”)
Now when we execute dataframe df the below output will be produced:

Creating Data Frame from .csv Files


A .csv file is a comma-separated values file that is similar to an Excel file but it takes less memory. We can create the
.csv file by saving the Excel file using the option: File -> Save As and type File name: empdata and Save as type: CSV
(Comma delimited)
We can read data from a .csv file using read_csv() function that takes the file path as:
import pandas as pd
df = pd.read_csv(“C://Users/admin/[Link]”)
Now when we execute dataframe df the below output will be produced:

13. Explain the following methods (any two) to create DataFrame with example:
i) Using .CSV file (refer question number 12.)
ii) Using Excel refer (question number 12.)
iii) Using Dictionary
iv) List of Tuples
Creating Data Frame from a Python Dictionary
It is possible to create a Python dictionary that contains employee data. Dictionary stores data in the form of key-value
pairs.
We take ‘empid’, ‘ename’, ‘sal’, ‘doj’, as keys and corresponding lists as values. Create a dictionary by the name
‘empdata’.
empdata ={ “empid”:[1001,1002,1003,1004,1005,1006],
“ename”:[“A”,”B”,”C”,”D”,”E”,”F”],
“sal”:[1000,2000,3000.45,9999.99,8888.88],
“doj”:[“10-10-2000”,”5-5-2001”,”2-2-2003”,”3-3-2003”,”4-2-2005”]}
We can read the dictionary using:
import pandas as pd
df = [Link](empdata)
the above dictionary of empdata will be created as the dataframe.
Creating Data Frame from Python List of Tuples
It is possible to create a list of tuples that contains employee data.
Create a list of 6 tuples by the name ‘empdata’.
Convert this list of tuples into a data frame by passing this tuple to DataFrame class object.
The original list of tuples does not have column names, we have to include the column names while creating the data
frame.

14. Explain any five operations on Dataframe with example.


1. Knowing Number of Rows and Columns
2. Retrieving Rows form Data Frame
3. Retrieving a Range of Rows
4. To Retrieve data from Column Names
5. Retrieving Data from Multiple Columns
6. Finding Maximum and Minimum Values
7. Displaying Statistical Information
8. Performing Queries on Data
9. Knowing the Index Range
10. Setting a column as Index
11. Resetting the Index
12. Sorting the data
Knowing Number of Rows and Columns
To know the number of rows and columns available in the data frame, we can use shape attribute. It returns a tuple that
contains number of rows and columns. We want to retrieve only rows or columns, we can read that number from the
tuple.

import pandas as pd
student = {
'Name': ['Aarav', 'Diya', 'Ishaan', 'Ananya'],
'Age': [25, 30, 35, 40],
'City': ['Mumbai', 'Delhi', 'Bengaluru', 'Chennai']
}
df = [Link](student)
--- DataFrame Content ---
Name Age City
0 Aarav 25 Mumbai
1 Diya 30 Delhi
2 Ishaan 35 Bengaluru
3 Ananya 40 Chennai
-------------------------
If we use shape attribute,
>>>[Link]
We get the output as, (4,3)
If we want to display only number of rows, or columns
rows, cols = [Link]
print(rows)
>>>4 #display only number of rows
Print(cols)
>>>3 #display only number of columns

Retrieving Rows from Data Frame


The method head() gives the first 5 rows, and the method tail() returns the last 5 rows.
To display only the first 2 rows, we can use head() method by passing 2 to it. Similarly, to display the last 2 rows, we
can use tail(2).
print("--- First 2 Rows (head) ---")
print([Link](2))
--- First 2 Rows (head) ---
Name Age City
0 Aarav 25 Mumbai
1 Diya 30 Delhi
print("--- Last 2 Rows (tail) ---")
print([Link](2))
--- Last 2 Rows (tail) ---
Name Age City
2 Ishaan 35 Bengaluru
3 Ananya 40 Chennai
Retrieving a Range of Rows
We can treat the data frame as an object and retrieve the rows from it using slicing.
For example,

import pandas as pd
data = {
'Name': ['Aarav', 'Diya', 'Ishaan', 'Ananya', 'Kabir', 'Meera'],
'Age': [25, 30, 35, 40, 45, 50], # Age list properly assigned
'City': ['Mumbai', 'Delhi', 'Bengaluru', 'Chennai', 'Hyderabad', 'Pune']
}
df = [Link](data)
print("--- Original DataFrame ---")
print(df)

--- Original DataFrame ---


Name Age City
0 Aarav 25 Mumbai
1 Diya 30 Delhi
2 Ishaan 35 Bengaluru
3 Ananya 40 Chennai
4 Kabir 45 Hyderabad
5 Meera 50 Pune
#Retrieve a specific range of rows (Index 1 to 3)
print("--- Slicing a Range (Index 1 to 3) ---")
print(df[1:4])

--- Slicing a Range (Index 1 to 3) ---


Name Age City
1 Diya 30 Delhi
2 Ishaan 35 Bengaluru
3 Ananya 40 Chennai

Display alternate rows (Step size of 2)


print("--- Alternate Rows (Every 2nd row) ---")
print(df[::2])

--- Alternate Rows (Every 2nd row) ---


Name Age City
0 Aarav 25 Mumbai
2 Ishaan 35 Bengaluru
4 Kabir 45 Hyderabad

egative step size slicing (Reversing the rows)


print("--- Negative Step Slicing (Reversed Order) ---")
print(df[::-1])

--- Negative Step Slicing (Reversed Order) ---


Name Age City
5 Meera 50 Pune
4 Kabir 45 Hyderabad
3 Ananya 40 Chennai
2 Ishaan 35 Bengaluru
1 Diya 30 Delhi
0 Aarav 25 Mumbai

To Retrieve data from Column Names


To get column data, we can mention the column name as subscript.
Ex: [Link] (Access the 'City' column using dot notation)
--- City Column Output ---
0 Mumbai
1 Delhi
2 Bengaluru
3 Chennai
4 Hyderabad
5 Pune
Name: City, dtype: object
The same can be done with bracket notation also. For example: df[city]. We get the same output:
--- City Column ---
0 Mumbai
1 Delhi
2 Bengaluru
3 Chennai
4 Hyderabad
5 Pune
Name: City, dtype: object
Retrieving Data from Multiple Columns
To retrieve multiple column data, we can provide the list of column names as subscript to data frame object as df[ [list
of column names]
df[['name',age]]
Name Age
0 Aarav 25
1 Diya 30
2 Ishaan 35
3 Ananya 40
4 Kabir 45
5 Meera 50
Finding Maximum and Minimum Values
It is possible to find the highest value using max() and the least value using min() method.
These methods are applied to columns containing numerical data. Ex: in the above example,
df['Age'].max() # 50 will be the output
df['Age'].min() #25 is the output

Displaying Statistical Information


We have describe() method that displays very important information like number of values, average, standard deviation,
minimum, maximum, 25%, 50% and 75% of the total value. This information is highly useful for statistical analysis.
[Link]()

Age
count 6.000000
mean 37.500000
std 9.354143
min 25.000000
25% 31.250000
50% 37.500000
75% 43.750000
max 50.000000

Performing Queries on Data


We can retrieve rows based on a query.
The query should be given as subscript in the data frame object.
To retrieve the row where salary is maximum.
Suppose, we want to show data from some columns based on a query, we can mention the list of columns and then the
query as : df[ [column names] ][query].

df[df['City'] == 'Mumbai']

Name Age City


0 Aarav 25 Mumbai

df[df['Age'] > 35]

Name Age City


3 Ananya 40 Chennai
4 Kabir 45 Hyderabad
5 Meera 50 Pune

Knowing the Index Range


The first column is called index column, and it is generated in the data frame automatically. We can retrieve the index
information using index attribute.
[Link]
the output will be,
RangeIndex(start=0, stop=6, step=1)

Setting a column as Index


We know that the index column is automatically generated. If we want to set a column from our data as index column,
that is possible using set_index() [Link] column with unique values can be set as index column.

import pandas as pd
data = {
'RollNumber': [101, 102, 103, 104, 105, 106],
'Name': ['Aarav', 'Diya', 'Ishaan', 'Ananya', 'Kabir', 'Meera'],
'Age':,
'City': ['Mumbai', 'Delhi', 'Bengaluru', 'Chennai', 'Hyderabad', 'Pune']
}
df = [Link](data)
print(df)

RollNumber Name Age City


0 101 Aarav 25 Mumbai
1 102 Diya 30 Delhi
2 103 Ishaan 35 Bengaluru
3 104 Ananya 40 Chennai
4 105 Kabir 45 Hyderabad
5 106 Meera 50 Pune

df1 = df.set_index('RollNumber')
the above statement sets Roll Number as the index instead of automatically generated number.
Name Age City
RollNumber
101 Aarav 25 Mumbai
102 Diya 30 Delhi
103 Ishaan 35 Bengaluru
104 Ananya 40 Chennai
105 Kabir 45 Hyderabad
106 Meera 50 Pune

The above statement creates another data frame ‘df1’ that uses ‘RollNumber’ as index column. However, the original
data frame ‘df’ is not modified and it still uses automatically generated index column. If we want to modify the original
‘df’ and set RollNumber as index column, we should add ‘inplace=True’. Once we set RollNumber as index, it is
possible to locate the data of any student by passing Roll number to loc attribute.

df.set_index('RollNumber', inplace=True)
Name Age City
RollNumber
101 Aarav 25 Mumbai
102 Diya 30 Delhi
103 Ishaan 35 Bengaluru
104 Ananya 40 Chennai
105 Kabir 45 Hyderabad
106 Meera 50 Pune

Using [Link][104] extracts the specific row corresponding to the roll number 104 (Ananya) from the DataFrame.

--- Output for [Link][104] ---


Name Ananya
Age 40
City Chennai

Resetting the Index


To reset the index value from ‘empid’ back to auto-generated index number, we can use reset_index() method with
‘inplace=True’ option.

df.reset_index(inplace=True)

--- DataFrame After reset_index() ---

RollNumber Name Age City


0 101 Aarav 25 Mumbai
1 102 Diya 30 Delhi
2 103 Ishaan 35 Bengaluru
3 104 Ananya 40 Chennai
4 105 Kabir 45 Hyderabad
5 106 Meera 50 Pune

Sorting the data

To sort your DataFrame, use the method name df.sort_values(). You must specify the column you want to sort by using
the by parameter.

df.sort_values(by='Age')

--- Sorted by Age (Ascending) ---


RollNumber Name Age City
0 101 Aarav 25 Mumbai
1 102 Diya 30 Delhi
2 103 Ishaan 35 Bengaluru
3 104 Ananya 40 Chennai
4 105 Kabir 45 Hyderabad
5 106 Meera 50 Pune

df.sort_values(by='Name', ascending=False)

--- Sorted by Name (Descending) ---

RollNumber Name Age City


5 106 Meera 50 Pune
4 105 Kabir 45 Hyderabad
2 103 Ishaan 35 Bengaluru
1 102 Diya 30 Delhi
3 104 Ananya 40 Chennai
0 101 Aarav 25 Mumbai

15. Write the required code for the following data retrieval in the DataFrame. Consider the DataFrame DF as:

a) To display all the employees ,where salary is below Rs20000


b) To display employee details ,whose salary is maximum .
c) To display name and salary of employees belongs to Sales
department.
d) To display the DataFrame in the reverse order.
e) To display only the column names .

import pandas as pd

# Creating DataFrame
data = {
'Empid' : [1001,1002,1003,1004,1005,1006],
'Name' : ['Ganesh Rao','Anil Kumar',
'Gaurav Guptha','HemaGuptha',
'Asha','Bobby'],
'Department' : ['Sales','Finance',
'Sales','Purchase',
'Finance','Sales'],
'Salary' : [10000,23000,18000,
20000,18000,25000]
}

df = [Link](data)

print("Original DataFrame")
print(df)
# a) Employees whose salary is below 20000
print("\nEmployees with salary below 20000")
print(df[df['Salary'] < 20000])

# b) Employee details whose salary is maximum


print("\nEmployee with maximum salary")
print(df[df['Salary'] == df['Salary'].max()])

# c) Display name and salary of Sales department employees


print("\nSales Department Employees")
print(df[['Name','Salary']]
[df['Department'] == 'Sales'])

# d) Display DataFrame in reverse order


print("\nDataFrame in Reverse Order")
print(df[::-1])

# e) Display only column names


print("\nColumn Names")
print([Link])

16. Explain with example, how data can be sorted in DataFrame.


Refer question number 14.

17. List and explain the steps with example to create Bar Graph using Matplot Library module.

A bar graph represents data in the form of vertical or horizontal bars. It is useful to compare the quantities.
Steps to create Bar graph:

1. Import the Plotting Module : Load the standard plotting sub-module pyplot from the matplotlib package.
2. Define the Data frame
We create data frame for constructing the Bar graph.
3. Extract x-axis and y-axis data
X-axis data: A list of student names or identifiers
Y-axis data: The corresponding overall academic percentage values
4. Construct bar graph
5. Pass your data variables directly into [Link](). When plotting percentages, it is helpful to use the width parameter
to control bar thickness and choose a professional color configuration
6. Set labels for x-axis and y-axis
Label your layout axes explicitly.
7. Set title for the bar graph
Add a descriptive heading in Bar graph.
8. Display the graph
Call the final visualization method [Link]() to process your script into a geometric display.
Ex:

# Step 1: Import the matplotlib sub-module


import [Link] as plt

# Step 2: Prepare student names (X) and final percentages (Y)


students = ['Rahul', 'Anjali', 'Kabir', 'Meera', 'Yash']
percentages = [78.5, 92.0, 64.2, 88.5, 81.0]

# Step 3: Build vertical bars with custom styling


[Link](students, percentages, color='royalblue', edgecolor='darkblue', width=0.5)

# Step 4: Layer on clear academic labels, headers, and set a fixed scale
[Link]('Student Names', fontsize=12, fontweight='bold', color='indigo')
[Link]('Final Term Percentage (%)', fontsize=12, fontweight='bold', color='indigo')
[Link]('Class XII Final Term Result Analysis', fontsize=14, fontweight='bold', color='darkgreen')

# Step 5: Render and display the visualization window


[Link]()
18. List and explain the steps with example to create Histogram using Matplot Library module.
Histograms show distributions of values. Histogram is like bar graph, but it is useful to show values grouped in bins or
intervals. Unlike a bar graph that compares discrete categories (like individual names or roll numbers), a histogram
shows data distribution [1]. It groups continuous numerical values (like marks, ages, or study hours) into ranges called
bins to show how frequently data falls into those ranges.

1. Import the Plotting Module - Load the standard plotting interface pyplot from your matplotlib package and alias it
as plt to keep your code compact
2. Prepare the Continuous Dataset - Gather a single collection or array of raw numerical student data.
Example data types: Final exam marks out of 100, weekly study hours, or student heights. You do not need matching
category names here; the histogram handles grouping the raw data automatically.

3. Construct the Histogram and Bins - Pass your dataset directly into [Link]().
bins: The number of intervals or ranges you want to divide your data into. You can provide an integer (e.g., bins=5) or a
specific range of intervals (e.g., bins=[40, 50, 60, 70, 80, 90, 100]).
color: Sets the fill color of your distribution bars.
edgecolor: Draws a visible border outline around the bars so you can distinguish where one bin ends and the next
begins.
4. Apply Distribution Labels –

[Link](): Explains the numerical ranges (e.g., "Marks Range").


[Link](): Shows the count or frequency (e.g., "Number of Students").
[Link](): Summarizes the purpose of the data assessment.

5. Render the Visual Output – call [Link]() to draw the histogram.

Ex:
# Step 1: Import the matplotlib sub-module
import [Link] as plt

# Step 2: Prepare raw continuous marks for 20 different students


student_marks = [72, 85, 45, 92, 67, 88, 79, 54, 61, 74,
81, 95, 48, 63, 71, 84, 58, 69, 77, 89]

# Define manual bin boundaries to group marks by 10s starting from 40 to 100
mark_bins = [40, 50, 60, 70, 80, 90, 100]

# Step 3: Build the histogram chart with customized bins and styling
[Link](student_marks, bins=mark_bins, color='mediumpurple', edgecolor='indigo')

# Step 4: Layer on frequency descriptive labels and headers


[Link]('Marks Ranges (Bins)', fontsize=12, fontweight='bold', color='midnightblue')
[Link]('Number of Students (Frequency)', fontsize=12, fontweight='bold', color='midnightblue')
[Link]('Grade Distribution Analysis of Class Test', fontsize=14, fontweight='bold', color='darkmagenta')

# Set explicit X-axis ticks to match our defined bin boundaries exactly
[Link](mark_bins)

# Step 5: Render and display the visualization window


[Link]()

19. List and explain the steps with example to Piechart using Matplot Library module.
A pie chart shows a circle that is divided into sectors and each sector represents a proportion of the whole.
A pie chart is a circular statistical graphic divided into slices to illustrate numerical proportion. Each slice represents a
specific category, and its size is directly proportional to the quantity it represents out of the whole (100%).
1. Import the Plotting Module - Load the core pyplot interface from your matplotlib package. Use the standard alias
plt
2. Prepare the Proportional Dataset –
A pie chart requires two coordinated collections of data:
• Numerical sizes (Values): A list of numbers that determine how large each slice of the pie will be.
• Labels (Categories): A list of strings matching the numbers to identify what each slice represents (e.g., student
streams or performance brackets).

3. Construct the Pie Layout

Pass your numerical data into [Link](). To make the chart readable, pass your categories into the labels
parameter. You can customize the look with these parameters:
• labels: The list of strings to display next to each slice.
• autopct: A string formatting string (like '%1.1f%%') that calculates and displays the percentage value right inside
each slice automatically.
• colors: A list of color strings or hex codes to apply distinct custom colors to each slice.
• startangle: Rotates the base of the circle. Setting startangle=90 starts the first slice at the top (12 o'clock position)
instead of the default right side (3 o'clock position).

4. Apply Academic Titles and Layout Adjustments –

[Link](): Add a descriptive title summarizing the distribution.

5. Render the Visual Output


Invoke the display command [Link]() to generate and present pie chart.
Ex:

# Step 1: Import the matplotlib sub-module


import [Link] as plt
# Step 2: Define categories (labels) and the number of students in each (sizes)
electives = ['Science', 'Commerce', 'Arts', 'Humanities']
student_count = [85, 60, 35, 20]

# Define a custom color palette for the slices


slice_colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']

# Step 3: Build the pie chart with customized formatting


[Link](student_count,
labels=electives,
autopct='%1.1f%%',
colors=slice_colors,
startangle=90)

# Step 4: Add a title and lock the aspect ratio to a perfect circle
[Link]('Distribution of Students by Elective Streams', fontsize=14, fontweight='bold', color='navy')

# Step 5: Render and display the visualization window


[Link]()

20. List and explain the steps with example to create Line Graph using Matplot Library module.
A line graph is a simple graph that shows the results in the form of [Link] create a line graph, we need x and y
coordinates.
1. Import the Plotting Module –
Load the standard plotting sub-module pyplot from the matplotlib package and alias it as plt.
2. Prepare the Ordered Dataset –

A line graph requires two matched lists where order matters:


• X-axis data: The progression tracking timeline (e.g., terms, months, or exam names).
• Y-axis data: The numerical metric tracking the performance corresponding to each point on the X-axis (e.g.,
marks, ranks, or test scores).

3. Plot the Line graph


Pass your X and Y datasets directly into the [Link]() function.
• marker: Adds visible symbol points at each data intersection (e.g., 'o' for circles, 's' for squares).
• linestyle: Modifies the connector lines (e.g., '-' for a solid line, '--' for a dashed line).
• linewidth: Sets the thickness of the path line.
• color: Applies a distinct color theme to the line and its markers.

4. Apply the Labels


• [Link](): Explains the chronological intervals or milestones on the horizontal axis.
• [Link](): Shows the quantitative unit being measured on the vertical axis.
• [Link](): Summarizes whose or what performance trend is being tracked.
• [Link](True): Adds background intersection lines to make tracking individual point positions easier.

5. Render the Visual Output

Invoke the command [Link]() to display the line graph.


# Step 1: Import the matplotlib sub-module
import [Link] as plt

# Step 2: Define tracking timeline (X) and corresponding quiz marks (Y)
unit_tests = ['Test 1', 'Test 2', 'Test 3', 'Test 4', 'Test 5']
aarav_marks = [34, 38, 35, 42, 47] # Score metrics out of 50

# Step 3: Build the line graph with specific markers and styling
[Link](unit_tests, aarav_marks, color='crimson', marker='o',
linestyle='-', linewidth=2, markersize=8)

# Step 4: Layer on clear progress labels, headers, and gridlines


[Link]('Monthly Unit Tests', fontsize=12, fontweight='bold', color='darkslategray')
[Link]('Marks Obtained (Out of 50)', fontsize=12, fontweight='bold', color='darkslategray')
[Link]("Aarav's Mathematics Academic Progress Trend", fontsize=14, fontweight='bold', color='darkblue')

# Add a background grid for structural readability


[Link](True, linestyle=':', alpha=0.6)

# Step 5: Render and display the visualization window


[Link]()

You might also like