Python
NumPy | The Absolute Basic for Beginners
Table of Contents
Introduction
Welcome to the absolute beginner’s guide to NumPy, brought to you by codesick.net!
NumPy, short for Numerical Python, stands as an indispensable open-source Python library, extensively employed in scientific and engineering domains. Within the NumPy library, you’ll discover powerful multidimensional array data structures such as the homogeneous, N-dimensional ndarray, and a large library of functions that operate efficiently on these data structures. Dive into the world of NumPy with us at codesick.net and unlock its full potential! Explore more about NumPy’s capabilities, and don’t hesitate to share your feedback or suggestions with us.
Installation
NumPy can be installed using pip, the Python package manager: ‘ pip install numpy ‘.
Pip install numpy
Alternatively, for users of Anaconda, NumPy comes pre-installed with the Anaconda distribution.
After installation, NumPy can be imported into Python scripts or interactive sessions using, ‘ import numpy as np ‘.
Import numpy as np
Array
An array is a data structure that stores a collection of elements, typically of the same data type, in contiguous memory locations. In programming, arrays are used to store multiple values under a single variable name, making it easier to manage and manipulate large sets of data.
numpy arrays provide additional functionality, memory efficiency, and performance advantages, especially for numerical computing tasks.
Creating Arrays
NumPy arrays are similar to Python lists but more efficient for numerical computations.
Import numpy as np
Array Indexing and Slicing
Accessing an array element is the same as array indexing. You can access an array element by referring to its index number.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Indexing
print(arr[0]) # Output: 1
print(arr[-1]) # Output: 5
In python, “slicing” refers to taking elements from one given index to another given index.
We pass slice instead of index like this: [start: end]
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Slicing
print(arr[1:4]) # Output: [2 3 4]
print(arr[:4]) # Output: [1 2 3 4]
print(arr[2:]) # Output: [3 4 5]
print(arr[-4:-1]) # Output: [2 3 4]
Array Operations
NumPy allows for element-wise mathematical operations on arrays.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Element-wise addition
result = arr1 + arr2 # Output: [5 7 9]
Array Shape and Reshaping
Arrays have a shape attribute indicating the size of each dimension or returns a tuple with each index having the number of corresponding elements.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr.shape) # Output: (3,3)
Reshaping means changing the shape of an array.
import numpy as np
arr0 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
#Reshape From 1-D to 2-D
arr1 = arr.reshape(4, 3)
print(arr1)
#Reshape From 1-D to 3-D
arr2 = arr.reshape(2, 2, 3)
print(arr2)
Array Aggregation
NumPy provides functions to aggregate array elements, such as np.sum() and np.mean().
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Compute sum of all elements
total_sum = np.sum(arr) # Output: 21
act_mean = np.mean(arr) # Output: 3.5
Array Concatenation and Splitting
NumPy offers functions to concatenate arrays and split them along specified axes.
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
# Concatenating along rows
newarr1 = np.concatenate((arr1, arr2), axis=0)
print(newarr1)
# Concatenating along columns
newarr2 = np.concatenate((arr1, arr2), axis=1)
print(newarr2)
When splitting along axis 0, the array is divided vertically, creating multiple sub-arrays with the same number of columns.
import numpy as np
# Create a 2D array
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Split along axis 0 (vertically)
split_result = np.vsplit(arr, 3)
# Output each sub-array
for sub_arr in split_result:
print(sub_arr)
When splitting along axis 1, the array is divided horizontally, creating multiple sub-arrays with the same number of rows.
import numpy as np
# Create a 2D array
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Split along axis 1 (horizontally)
split_result = np.hsplit(arr, 3)
# Output each sub-array
for sub_arr in split_result:
print(sub_arr)
Broadcasting
Broadcasting allows NumPy to perform arithmetic operations on arrays of different shapes.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 2
# Broadcasting scalar to array
result = arr * scalar # Output: [[ 2 4 6] [ 8 10 12]]
Conclusion
NumPy provides a powerful foundation for numerical computing in Python.
Mastering NumPy’s basics is essential for anyone working with data or scientific computing in Python.