This program shows how to get and change parts of a 2D array using indexing. It prints specific values and the updated array.
NumPy
import numpy as np
# Create a 2D array
data = np.array([[5, 10, 15],
[20, 25, 30],
[35, 40, 45]])
# Get the value in the first row, second column
value = data[0, 1]
print(f"Value at row 0, column 1: {value}")
# Get the entire second row
second_row = data[1, :]
print(f"Second row: {second_row}")
# Get the last column
last_column = data[:, 2]
print(f"Last column: {last_column}")
# Change the value at row 2, column 0
data[2, 0] = 100print("Updated data:")
print(data)
OutputSuccess
Important Notes
Remember that indexing starts at 0, not 1.
Using slicing (start:stop) does not include the stop index.
Changing values by indexing updates the original array.
Summary
Indexing lets you pick specific data quickly.
You can get single values, rows, columns, or slices.
Indexing helps you change data easily and efficiently.
Practice
(1/5)
1. What does indexing in NumPy allow you to do?
easy
A. Create new arrays from scratch
B. Select specific elements or slices from an array
C. Automatically sort the array elements
D. Convert arrays into lists
Solution
Step 1: Understand the purpose of indexing
Indexing is used to access specific parts of an array, like single elements or slices.
Step 2: Compare with other options
Creating new arrays, sorting, or converting are different operations, not indexing.
Final Answer:
Select specific elements or slices from an array -> Option B
Quick Check:
Indexing = selecting parts of array [OK]
Hint: Indexing means picking parts of data quickly [OK]
Common Mistakes:
Confusing indexing with array creation
Thinking indexing sorts data
Mixing indexing with data type conversion
2. Which of the following is the correct syntax to get the first element of a NumPy array arr?
easy
A. arr.first()
B. arr(0)
C. arr[0]
D. arr{0}
Solution
Step 1: Recall NumPy indexing syntax
NumPy arrays use square brackets with zero-based indices to access elements.
Step 2: Check each option
Only arr[0] uses correct square brackets and zero index; others are invalid syntax or methods.
Final Answer:
arr[0] -> Option C
Quick Check:
First element = arr[0] [OK]
Hint: Use square brackets and zero-based index [OK]