Python NumPy Arrays
In this page:
Creating Arrays with Functions
NumPy provides dedicated constructor functions instead of building arrays from Python lists by hand: np.zeros(shape) and np.ones(shape) create arrays pre-filled with a constant, while np.arange() and np.linspace() generate evenly spaced numeric ranges directly as arrays.
Example: Creating Arrays with Functions
import numpy as np
print(np.zeros(3))
print(np.arange(0, 10, 2))
Slicing and Indexing
Indexing and slicing a NumPy array follows the same array[start:stop:step] syntax as a Python list, but extends naturally to multiple dimensions with comma-separated indices like array[row, col]. Slices of NumPy arrays are *views* onto the original data by default, not independent copies, so modifying a slice can modify the source array too.
Example: Slicing and Indexing
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr[0, 1])
print(arr[:, 0])
Reshaping and Resizing
.reshape() changes how an array's existing data is organized into dimensions -- turning a flat 12-element array into a 3x4 grid, for instance -- without copying or altering any of the underlying values, as long as the new shape's total element count matches the original.
Example: Reshaping and Resizing
import numpy as np
arr = np.arange(12)
print(arr.reshape(3, 4))
Array Stacking and Splitting
np.concatenate() (or the more specific np.vstack()/np.hstack()) joins multiple arrays together along a chosen axis, while np.split() divides one array into several smaller ones. These are the array equivalents of combining or breaking apart lists, but operating on whole numeric blocks at once.
Example: Array Stacking and Splitting
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
print(np.concatenate([a, b]))
Conditional Selection
Boolean indexing lets you select array elements using a condition directly, like array[array > 10], which builds a boolean mask and returns only the elements where that mask is True. This replaces manual filtering loops with a single expressive line that NumPy executes at compiled speed.
Example: Conditional Selection
import numpy as np
arr = np.array([5, 15, 25])
print(arr[arr > 10])
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Python NumPy Introduction
- Python NumPy Arrays
- Python Pandas Introduction
- Python Pandas DataFrame
- Python Matplotlib Basics
- Python Data Visualization
- Python Statistics Module
- Python CSV & Data Analysis
- Python requests Module
- Python JSON & APIs
- Python Web Scraping Basics
- Python Flask Introduction
- Python Django Introduction
- Python MongoDB