Q1 (5 Marks) – Array Creation & Indexing
1. Create a 6×6 array of random integers between 10 and 99.
2. Extract:
o The last two rows
o The first three columns
o Elements at positions where both row and column indices are even
3. Print the shape of each extracted result.
import numpy as np
a = [Link](10, 100, (6,6))
print(a)
print(a[-2:]) # Last two rows
print(a[:, :3]) # First three columns
print(a[::2, ::2]) # Even row and even column indices
print(a[-2:].shape)
print(a[:, :3].shape)
print(a[::2, ::2].shape)
Q2 (5 Marks) – Slicing & Views
1. Extract a 3×3 submatrix from the center of the array.
2. Modify all its values to 0.
3. Check whether the original array changes.
4. Explain the reason for this behavior.
import numpy as np
# Create a 6x6 array with random integers from 10 to 99
a = [Link](10, 100, (6, 6))
# Display the original array
print(a)
# Extract the 3x3 center submatrix
b = a[1:4, 1:4]
# Display the submatrix
print(b)
# Modify all elements of the submatrix to 0
b[:] = 0
# Display the modified submatrix
print(b)
# Display the original array to check whether it changes
print(a)
a[1:4, 1:4] extracts the center 3×3 submatrix.
b[:] = 0 changes all elements of the submatrix to 0.
The original array also changes because slicing in NumPy returns a view that shares memory
with the original array.
Q3 (5 Marks) – Boolean Indexing
1. Select all elements greater than the mean of the array.
2. Count how many such elements exist.
3. Reshape them into a 2-column matrix (if possible).
Handle the case where reshaping is not possible
import numpy as np
# Create a 6x6 array with random integers from 10 to 99
a = [Link](10, 100, (6, 6))
# Display the original array
print(a)
# Calculate the mean of the array
mean = [Link]()
# Select elements greater than the mean
b = a[a > mean]
# Display elements greater than mean
print(b)
# Count the number of such elements
print(len(b))
# Reshape into 2 columns if possible
if len(b) % 2 == 0:
c = [Link](-1, 2)
print(c)
else:
print("Reshaping not possible")
Q4 (5 Marks) – Broadcasting
1. Compute the mean of each row.
2. Subtract the row mean from each element of that row.
3. Print the resulting matrix.
4. Explain how broadcasting works in this case.
import numpy as np
# Create a 6x6 array with random integers from 10 to 99
a = [Link](10, 100, (6, 6))
# Display the original array
print(a)
# Compute mean of each row
row_mean = [Link](axis=1)
# Display row means
print(row_mean)
# Subtract row mean from each element of that row
b = a - row_mean[:, [Link]]
# Display the resulting matrix
print(b)
# [Link](axis=1) calculates the mean of each row.
# [Link] converts row_mean from a 1D array to a column vector.
# Broadcasting automatically expands the column vector
# to match the shape of the array and performs subtraction.
# This avoids using loops and makes computations faster.
🔹 Basic Level
1. What is NumPy? Why is it faster than Python lists?
Answer:
NumPy is a Python library used for numerical computations and multidimensional array
operations. It is faster than Python lists because it stores homogeneous data in contiguous
memory and uses optimized C implementations.
2. What is an ndarray?
Answer:
ndarray (N-dimensional array) is the main data structure in NumPy used to store homogeneous
data in one or more dimensions.
3. Difference between Python list and NumPy array?
Python List NumPy Array
Stores mixed data types Stores same data type
Slower Faster
More memory usage Less memory usage
No vectorized operations Supports vectorized operations
4. What is the use of shape, size, and dtype?
shape → Returns dimensions of the array.
size → Returns total number of elements.
dtype → Returns data type of array elements.
Example:
[Link]
[Link]
[Link]
5. How do you create a 2D array?
import numpy as np
a = [Link]([[1,2,3],
[4,5,6]])
🔹 Indexing & Slicing
6. Difference between indexing and slicing?
Indexing Slicing
Returns a single element Returns multiple elements
Example: a[1,2] Example: a[1:3,0:2]
Dimension may reduce Dimension usually remains same
7. What happens if you use negative indexing?
Negative indexing accesses elements from the end of the array.
Example:
a[-1]
returns the last row.
8. How do you extract alternate rows and columns?
a[::2, ::2]
This selects every second row and every second column.
9. What does step size mean in slicing?
Step size specifies the interval between elements selected.
Example:
a[0:6:2]
selects elements at indices 0, 2 and 4.
10. Why does slicing not give an IndexError even with large step values?
Because slicing automatically adjusts the range within valid indices and returns available
elements only.
🔹 Boolean & Fancy Indexing
11. What is Boolean indexing?
Selecting array elements using a condition is called Boolean indexing.
Example:
a[a > 50]
returns all elements greater than 50.
12. Why does Boolean indexing return a 1D array?
Because NumPy collects all matching elements sequentially into a one-dimensional array.
13. Difference between Fancy indexing and Slicing?
Fancy Indexing Slicing
Uses index arrays Uses ranges
Returns a copy Returns a view
More flexible Faster
Example:
a[[0,2,4]]
14. Why can Fancy indexing return a copy instead of a view?
Because fancy indexing creates a new array in memory instead of sharing memory with the
original array.
15. Which is faster: Boolean indexing or slicing? Why?
Slicing is faster because it returns a view and does not create a new array.
🔹 View vs Copy
16. What is the difference between a view and a copy?
View Copy
Shares memory with original Separate memory
Changes affect original Changes do not affect original
Faster Slightly slower
17. How can you check if two arrays share memory?
np.shares_memory(a, b)
Returns True if both arrays share memory.
18. When does slicing return a copy?
Normally slicing returns a view.
It returns a copy only when .copy() is explicitly used.
Example:
b = a[1:3].copy()
19. Why is modifying a sliced array sometimes dangerous?
Because slices share memory with the original array, modifications in the slice also change the
original array unintentionally.
20. How can you force a deep copy?
b = [Link]()
This creates a completely independent array.
🔹 Broadcasting
21. What is broadcasting?
Broadcasting is the automatic expansion of smaller arrays to match larger arrays during
arithmetic operations.
22. What are the rules of broadcasting?
Two dimensions are compatible if:
1. They are equal, or
2. One of them is 1.
Otherwise broadcasting fails.
23. Why does subtracting row mean sometimes fail?
Because of shape mismatch.
For example:
[Link] # (6,6)
row_mean.shape # (6,)
To make broadcasting work:
row_mean[:, [Link]]
which converts shape to (6,1).
24. What does axis=0 and axis=1 mean?
axis=0 → Operation is performed column-wise.
axis=1 → Operation is performed row-wise.
Example:
[Link](axis=0) # Column means
[Link](axis=1) # Row means
25. Why is broadcasting efficient?
Broadcasting avoids creating duplicate copies of data and eliminates explicit loops, making
computations faster and memory efficient.
PANDAS
Employee,Department,Age,Salary,Experience
Asha,IT,25,50000,2
Rahul,HR,35,60000,8
Ravi,Finance,40,70000,10
Priya,IT,32,65000,7
Sneha,HR,28,45000,3
Kiran,Finance,38,80000,12
Anil,IT,45,90000,15
Meena,HR,31,55000,6
Q5 (5 Marks) – Reading & Inspection
1. Load the CSV file into a DataFrame.
2. Display data types of all columns.
3. Check for missing values.
4. Convert Salary to numeric if required.
import pandas as pd
# Load CSV file
df = pd.read_csv("[Link]")
# Display data types
print([Link])
# Check missing values
print([Link]().sum())
# Convert Salary to numeric
df["Salary"] = pd.to_numeric(df["Salary"])
Q6 (5 Marks) – Data Filtering
Display employees who:
Are older than 30
Earn above overall average salary
Have experience greater than 5 years
Sort the result by Salary (descending).
import pandas as pd
df = pd.read_csv("[Link]")
# Calculate average salary
avg_salary = df["Salary"].mean()
# Apply filtering conditions
result = df[(df["Age"] > 30) &
(df["Salary"] > avg_salary) &
(df["Experience"] > 5)]
# Sort by Salary in descending order
result = result.sort_values(by="Salary",
ascending=False)
print(result)
Q7 (5 Marks) – GroupBy Analysis
1. Find department-wise average salary.
2. Find department-wise maximum experience.
Identify the department with highest salary variance
import pandas as pd
df = pd.read_csv("[Link]")
# Department-wise average salary
print([Link]("Department")
["Salary"].mean())
# Department-wise maximum experience
print([Link]("Department")
["Experience"].max())
# Salary variance
variance = [Link]("Department")["Salary"].var()
# Department with highest variance
print([Link]())
Q8 (5 Marks) – New Column Creation
1. Create a column:
Performance Score = (Salary ÷ Experience) × Age
2. Normalize this score using Min-Max scaling.
Display top 3 employees based on normalized score
import pandas as pd
df = pd.read_csv("[Link]")
# Create Performance Score
df["Performance Score"] = (
df["Salary"] /
df["Experience"]
) * df["Age"]
# Normalize using Min-Max Scaling
df["Normalized Score"] = (
(df["Performance Score"] -
df["Performance Score"].min())
(df["Performance Score"].max() -
df["Performance Score"].min())
# Display top 3 employees
print([Link](3, "Normalized Score"))
Q9 (5 Marks) – Series & Indexing
1. Extract the Salary column as a Series.
2. Demonstrate difference between:
o Label-based indexing
o Position-based indexing
Explain why using improper indexing can cause errors.
import pandas as pd
df = pd.read_csv("[Link]")
# Extract Salary as Series
salary = df["Salary"]
print(salary)
# Label-based indexing
print([Link][0])
# Position-based indexing
print([Link][0])
PART B – Pandas Viva Questions
🔹 Basics
1. What is Pandas?
Pandas is an open-source Python library used for data manipulation, analysis, and handling tabular
data.
2. Difference between Series and DataFrame?
Series DataFrame
One-dimensional Two-dimensional
Single column Multiple columns
Homogeneous data Different data types
3. What is an index in Pandas?
An index is a label used to identify rows in a Series or DataFrame.
Example:
[Link]
4. How is Pandas different from NumPy?
Pandas NumPy
Used for tabular data Used for numerical arrays
Supports labels No labels
Mixed data types allowed Homogeneous data
Built on NumPy Base library
5. When should you use NumPy instead of Pandas?
Use NumPy for numerical computations, matrix operations, and high-speed array processing.
🔹 CSV Handling
6. How do you read a CSV file?
import pandas as pd
df = pd.read_csv("[Link]")
7. Why might numeric data be stored as object type?
Because the column may contain:
Missing values
Text values
Special characters
Currency symbols
8. How do you handle missing values?
To check:
[Link]().sum()
To remove:
[Link]()
To replace:
[Link](0)
9. Difference between head() and tail()?
head() tail()
Displays first 5 rows Displays last 5 rows
Used to inspect beginning Used to inspect end
10. How do you check data types of columns?
[Link]
or
[Link]()
🔹 Filtering & Conditions
11. Why does and not work for filtering in Pandas?
Because and works only with single Boolean values.
For Pandas columns, use:
&
Example:
df[(df["Age"]>30) &
(df["Salary"]>50000)]
12. Why must conditions be inside parentheses?
Because & and | have higher precedence.
Correct:
(df["Age"]>30) &
(df["Salary"]>50000)
13. Difference between loc and iloc?
loc iloc
Label-based indexing Position-based indexing
Uses labels Uses integer positions
Example:
[Link][0]
[Link][0]
14. What is label-based indexing?
Selecting rows and columns using labels is called label-based indexing.
It is performed using:
loc
Example:
[Link][0]
15. What is position-based indexing?
Selecting rows and columns using integer positions is called position-based indexing.
It is performed using:
iloc
Example:
[Link][0]
🔹 GroupBy & Aggregation
16. What is GroupBy?
GroupBy groups rows having similar values and performs aggregate operations.
Example:
[Link]("Department")
17. Difference between aggregate() and transform()?
aggregate() transform()
Returns summarized result Returns same size as original
Used for statistics Used for modifying data
18. How do you calculate department-wise average salary?
[Link]("Department")["Salary"].mean()
19. How do you calculate variance?
df["Salary"].var()
Department-wise:
[Link]("Department")["Salary"].var()
20. Why is GroupBy powerful?
Because it follows:
Split → Apply → Combine
and allows efficient analysis of grouped data.
🔹 Chained Indexing
21. What is chained indexing?
Using multiple indexing operations one after another.
Example:
df[df["Age"]>30]["Salary"]
22. What is SettingWithCopyWarning?
It is a warning generated when Pandas is unsure whether modifications are made on the original
DataFrame or its copy.
23. Why is .loc[] safer?
Because .loc[] directly modifies the original DataFrame and avoids ambiguity.
Example:
[Link][df["Age"]>30,
"Salary"] = 50000
24. Give a scenario where chained indexing fails silently.
df[df["Age"]>30]["Salary"] = 50000
This may not update the original DataFrame.
25. How can you avoid this issue?
Use:
[Link][df["Age"]>30,
"Salary"] = 50000
instead of chained indexing.
🔹 Data Analysis Concepts
26. What is normalization?
Normalization scales data into a fixed range, usually 0 to 1.
Formula:
' X−X min
X=
X max− X min
27. What is standardization?
Standardization transforms data so that:
Mean = 0
Standard Deviation = 1
Formula:
X−μ
Z=
σ
28. Difference between Min-Max Scaling and Z-score?
Min-Max Scaling Z-Score
Range 0 to 1 Mean=0, Std=1
Sensitive to outliers Less sensitive
Used in Neural Networks Used in Statistical models
29. When should you normalize data?
Normalize data when:
Features have different ranges.
Using KNN.
Using Neural Networks.
Using Gradient Descent.
30. Why can dividing by experience introduce bias?
Employees with very low experience may get extremely high scores after division, resulting in
misleading analysis. Therefore, such formulas should be used carefully.
MATPLOTLIB
months = ['Jan','Feb','Mar','Apr','May','Jun']
it = [100,150,170,200,220,250]
hr = [90,120,160,180,220,240]
finance = [110,140,180,210,230,260]
Q10 (5 Marks) – Line Plot with Markers
1. Plot sales of all three departments in one graph.
2. Use:
o IT → dashed line with circle markers
o HR → dotted line with square markers
o Finance → solid line with triangle markers
3. Add title, legend, grid, and axis labels.
import [Link] as plt
months = ['Jan','Feb','Mar','Apr','May','Jun']
it = [100,150,170,200,220,250]
hr = [90,120,160,180,220,240]
finance = [110,140,180,210,230,260]
[Link](months,it,'--o',label='IT')
[Link](months,hr,':s',label='HR')
[Link](months,finance,'-^',label='Finance')
[Link]("Department Sales")
[Link]("Months")
[Link]("Sales")
[Link]()
[Link](True)
[Link]()
Q11 (5 Marks) – Subplots
1. Create a 2×2 subplot grid.
2. Plot IT, HR, Finance in three separate subplots.
3. Plot combined comparison in the fourth subplot.
4. Ensure proper titles and layout adjustment.
import [Link] as plt
months = ['Jan','Feb','Mar','Apr','May','Jun']
it = [100,150,170,200,220,250]
hr = [90,120,160,180,220,240]
finance = [110,140,180,210,230,260]
fig, ax = [Link](2,2)
ax[0,0].plot(months,it)
ax[0,0].set_title("IT")
ax[0,1].plot(months,hr)
ax[0,1].set_title("HR")
ax[1,0].plot(months,finance)
ax[1,0].set_title("Finance")
ax[1,1].plot(months,it,label='IT')
ax[1,1].plot(months,hr,label='HR')
ax[1,1].plot(months,finance,label='Finance')
ax[1,1].legend()
ax[1,1].set_title("Comparison")
plt.tight_layout()
[Link]()
Q12 (5 Marks) – Data Interpretation
1. Highlight the highest sales month for IT.
2. Annotate the point where HR sales first exceed 200.
3. Briefly interpret overall sales trend.
import [Link] as plt
months=['Jan','Feb','Mar','Apr','May','Jun']
it=[100,150,170,200,220,250]
hr=[90,120,160,180,220,240]
[Link](months,it,label='IT')
[Link](months,hr,label='HR')
# Highest sales month for IT
max_it=max(it)
index_it=[Link](max_it)
[Link](months[index_it],max_it)
# HR first exceeds 200
for i in range(len(hr)):
if hr[i]>200:
[Link]("HR > 200",
(months[i],hr[i]))
break
[Link]()
[Link](True)
[Link]()
Basics
1. What is Matplotlib?
Matplotlib is a Python library used for creating graphs, charts, and data visualizations.
2. Difference between plot() and scatter()?
plot() scatter()
Draws line graph Draws individual points
Points are connected Points are not connected
Used to show trends Used to show relationships
3. What are markers?
Markers are symbols used to represent data points on a graph.
Examples:
Marker Meaning
o Circle
s Square
^ Triangle
Marker Meaning
* Star
Example:
[Link](x, y, 'o')
4. What are line styles?
Line styles determine the appearance of lines.
Style Meaning
'-' Solid line
'--' Dashed line
':' Dotted line
'-.' Dash-dot line
Example:
[Link](x, y, '--')
5. Why do we use legends?
Legends help identify different lines or plots in a graph.
Example:
[Link]()
🔹 Subplots
6. Difference between subplot() and subplots()?
subplot() subplots()
Creates one subplot at a time Creates multiple subplots together
Older method Preferred method
Returns nothing Returns figure and axes
Example:
[Link](2,2,1)
fig, ax = [Link](2,2)
7. What does a 2×2 subplot grid mean?
It means:
2 rows
2 columns
Total = 4 subplots
Example:
fig, ax = [Link](2,2)
8. How do you share axes?
Using:
[Link](2,2,sharex=True,sharey=True)
This shares x-axis and y-axis among all subplots.
9. Why is layout adjustment needed?
Layout adjustment prevents:
Overlapping titles
Overlapping labels
Cropped plots
Example:
plt.tight_layout()
10. What happens if subplots overlap?
Titles may overlap.
Axis labels may become unreadable.
Graphs may appear cluttered.
Using
plt.tight_layout()
solves this problem.
🔹 Visualization Concepts
11. What is log scale?
A logarithmic scale represents values using logarithms instead of equal intervals.
Example:
[Link]('log')
or
[Link]('log')
12. When should a secondary y-axis be used?
When two datasets:
Have different units
Have very different ranges
Example:
Temperature and rainfall.
13. Why can dual axes be misleading?
Because changing the scale can make unrelated trends appear similar or hide actual differences.
14. Why is a truncated y-axis dangerous?
A truncated y-axis does not start at zero.
It may exaggerate small differences and mislead the viewer.
15. Why should data visualization be honest?
Because graphs should accurately represent data and avoid misleading interpretations.
Honest visualization:
Uses proper scales.
Avoids distortion.
Clearly labels axes.
Represents data truthfully.
🔥 Important Viva Questions
16. How do you display a graph?
[Link]()
17. How do you add a title to a graph?
[Link]("Sales Graph")
18. How do you label x-axis and y-axis?
[Link]("Months")
[Link]("Sales")
19. How do you add grid lines?
[Link](True)
20. How do you save a graph as an image?
[Link]("[Link]")
This saves the graph as an image file.