Unit4 - Python QN Bank Solved
Unit4 - Python QN Bank Solved
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.
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
import pandas as pd
# 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 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.
#crete a cursor
cursorObj = [Link]()
#Deleting
[Link]("Delete from STUDENT where name='Vaishnavi' ")
>>> [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.
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.
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
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.
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.
1. Addition of Arrays
Definition
In addition, the corresponding elements of two arrays are added together.
Example
import numpy as np
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
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
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
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).
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.
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
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
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.
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
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
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
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:
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.
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
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)
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
df[df['City'] == 'Mumbai']
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)
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.
df.reset_index(inplace=True)
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')
df.sort_values(by='Name', ascending=False)
15. Write the required code for the following data retrieval in the DataFrame. Consider the DataFrame DF as:
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])
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 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')
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 –
Ex:
# Step 1: Import the matplotlib sub-module
import [Link] as plt
# 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')
# Set explicit X-axis ticks to match our defined bin boundaries exactly
[Link](mark_bins)
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).
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).
# 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')
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 –
# 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)