Module: M2-R5: Web Design & Publishing
Chapter: Ch1 Computer Intro
NumPy arrays can be accessed and manipulated using indexing and slicing, similar to Python lists, but with powerful features for multi-dimensional arrays.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # First element
print(arr[-1]) # Last element
Output:
10
50
print(arr[1:4]) # Elements from index 1 to 3
print(arr[:3]) # First 3 elements
print(arr[2:]) # From index 2 to end
print(arr[::2]) # Every second element
Output:
[20 30 40]
[10 20 30]
[30 40 50]
[10 30 50]
arr2d = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
print(arr2d[0,0]) # First row, first column
print(arr2d[1,2]) # Second row, third column
Output:
1
6
print(arr2d[:2,1:]) # First two rows, last two columns
print(arr2d[::2, ::2]) # Every other row and column
Output:
[[2 3]
[5 6]]
[[1 3]
[7 9]]