Array Indexing & Reshaping
-
Learn how to access, slice, and reshape NumPy arrays for flexible data analysis.
- Indexing & Slicing
What is Indexing?
Indexing is used to access individual elements of a NumPy array using their position (index).
Indexing starts from 0
Negative indexing accesses elements from the end
Example – Indexing in 1D Array
NumPy Array Indexing Example
This code shows how to access elements of a NumPy array using positive and negative indexing to retrieve values from specific positions.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # 10
print(arr[2]) # 30
print(arr[-1]) # 50
What is Slicing?
Slicing is used to extract a portion of an array.
Syntax:
array[start : end : step]
Example – Slicing 1D Array
print(arr[1:4]) # [20 30 40]
print(arr[:3]) # [10 20 30]
print(arr[::2]) # [10 30 50]
Indexing in 2D Arrays
arr2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(arr2d[0, 1]) # 2
print(arr2d[2, 0]) # 7
Slicing in 2D Arrays
print(arr2d[0:2, 1:3])
Output:
[[2 3]
[5 6]]
Why Indexing & Slicing is Important
Extract required data quickly
Perform calculations on subsets
Reduce memory usage
Essential for data preprocessing
Reshaping Arrays
What is Reshaping?
Reshaping means changing the shape (dimensions) of an array without changing its data.
Rule for Reshaping
Total number of elements must remain the same.
Example – Reshaping 1D to 2D
arr = np.array([1, 2, 3, 4, 5, 6])
new_arr = arr.reshape(2, 3)
print(new_arr)
Output:
[[1 2 3]
[4 5 6]]
Reshaping Using -1
NumPy automatically calculates the dimension when -1 is used.
arr.reshape(3, -1)
Flattening an Array
arr2d.flatten()
Converting 2D to 1D
arr2d.reshape(-1)
Common Reshape Operations
Example – Transpose
arr2d.T
Real-World Use Cases
Image processing (pixels reshaping)
Machine learning datasets
Data cleaning & transformation
Matrix calculations