Lecture
Indexing and Slicing Arrays
After creating an array, you’ll often need to access individual elements or extract specific sections.
This process is called indexing and slicing.
Indexing
Indexing retrieves individual items based on their position.
Like Python lists, NumPy arrays use zero-based indexing — the first element is at position 0.
Indexing a 1D Array
arr = np.array([10, 20, 30, 40]) print(arr[1]) # Output: 20
For 2D arrays, use two indices: arr[row, column].
Indexing a 2D Array
matrix = np.array([[1, 2], [3, 4]]) print(matrix[1, 0]) # Output: 3
Slicing
Slicing allows you to select a range of elements using the : operator.
Slicing a 1D Array
arr = np.array([10, 20, 30, 40, 50]) print(arr[1:4]) # Output: [20 30 40]
You can also slice rows or columns in 2D arrays.
Slicing a 2D Array
matrix = np.array([[1, 2, 3], [4, 5, 6]]) print(matrix[:, 1]) # Output: [2 5]
Lessons in this chapter · NumPy Essentials for Data Analysis
- 1. What is NumPy and Why Use It?
- 2. Creating 1D and 2D Arrays
- 3. Indexing and Slicing Arrays
- 4. Array Arithmetic and Broadcasting
- 5. Boolean Masking and Filtering
- 6. Array Shapes, Axes, and Broadcasts
- 7. Multiple-choice quiz
- 8. Aggregation Functions (sum, mean, std, etc.)
- 9. Array Reshaping and Flattening
- 10. Generating Arrays (arange, linspace, zeros, ones)
- 11. Data Type Conversion and Copying Arrays
- 12. Working with Multidimensional Arrays
- 13. Fill-in-the-blank quiz
Quiz
0 / 1
How do you slice a 2D NumPy array to access a specific column?
To slice the second column of a 2D NumPy array, use the syntax: matrix[:, ]
0
1
2
3
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help