Introduction
If you're venturing into Python for data science, machine learning, or scientific computing, NumPy is an indispensable library you'll encounter. Short for Numerical Python, NumPy provides support for large, multi-dimensional arrays and matrices, along with a collection of high-level mathematical functions to operate on these arrays.
๐ Why Use NumPy?
Python lists are flexible but not efficient for numerical operations on large data. NumPy arrays are faster, more compact, and offer rich functionality.
Example: Performance Comparison
import numpy as npimport time
size = 1_000_000list1 = list(range(size))array1 = np.arange(size)
# List operationstart = time.time()list_sum = [x + 1 for x in list1]print("List time:", time.time() - start)
# NumPy array operationstart = time.time()array_sum = array1 + 1print("NumPy time:", time.time() - start)
๐ง Key Features of NumPy
1. N-Dimensional Arrays (ndarray)
import numpy as np
arr_1d = np.array([1, 2, 3])
arr_2d = np.array([[1, 2], [3, 4]])
print("1D Array:", arr_1d)
print("2D Array:\n", arr_2d)
2. Broadcasting
import numpy as np
a = np.array([1, 2, 3])
b = 2
print("Broadcasted Result:", a * b) # Multiplies each element by 2
3. Vectorized Operations
data = np.array([10, 20, 30])
mean = np.mean(data)
print("Mean:", mean)
print("Centered Data:", data - mean)
4. Random Number Generation
random_array = np.random.rand(3, 2)
print("Random Array:\n", random_array)
5. Reshaping and Slicing Arrays
a = np.arange(12)
reshaped = a.reshape(3, 4)
print("Reshaped Array:\n", reshaped)
# Slicing
print("Second row:", reshaped[1])
print("Element at (2,3):", reshaped[2, 3])
๐ ️ Installing NumPy
pip install numpy
Or using Anaconda:
conda install numpy
๐ Additional Resources
NumPy Official Docs
NumPy on W3Schools
NumPy on GeeksforGeeks
✍️ Final Thoughts
NumPy simplifies complex operations with clean syntax and blazing speed. Whether you're a data science newbie or an experienced developer, NumPy is a must-have tool in your Python arsenal.
No comments:
Post a Comment