NumPy (Numerical Python) is the main package for scientific computing in Python. It performs a wide variety of advanced mathematical operations with high efficiency. In this guide, you’ll learn several key NumPy functions including creating arrays, slicing, indexing, reshaping, and stacking.
NumPy arrays are faster and more compact than Python lists, making them essential for large-scale mathematical operations. Check out the official NumPy documentation for comprehensive details.
Arrays are one of the core data structures of the NumPy library. You can think of them as a grid of values, all of the same type. While Python lists are convenient for storing different data types, NumPy arrays offer significant advantages:
Performance
NumPy arrays are much faster than Python lists, especially for large datasets
Memory Efficiency
Arrays take up less space and process data more efficiently
Built-in Functions
Extensive API with mathematical operations requiring only a few lines of code
Uniform Type
All elements are of the same type, enabling optimized operations
# Number of dimensionsprint(multi_dim_arr.ndim) # Output: 2# Shape (rows, columns)print(multi_dim_arr.shape) # Output: (2, 3)# Total number of elementsprint(multi_dim_arr.size) # Output: 6
If omitted, defaults to length of array (end-exclusive)
3
Step Size
If omitted, defaults to 1
a = np.array([1, 2, 3, 4, 5])# Get elements from index 1 to 3sliced_arr = a[1:4]print(sliced_arr) # Output: [2 3 4]# Get first three elementssliced_arr = a[:3]print(sliced_arr) # Output: [1 2 3]# Get last three elementssliced_arr = a[2:]print(sliced_arr) # Output: [3 4 5]# Get every second elementsliced_arr = a[::2]print(sliced_arr) # Output: [1 3 5]
# Split horizontally into 2 arrayshorz_split_two = np.hsplit(horz_stack, 2)print(horz_split_two)# Split vertically into 2 arraysvert_split_two = np.vsplit(vert_stack, 2)print(vert_split_two)
Use np.hsplit() and np.vsplit() to split arrays into smaller pieces. You can specify the number of equal sections or the indices where splits should occur.