Whether you're diving into data science, machine learning, or scientific computing, NumPy is one of the most essential Python libraries you’ll use. In this article, we’ll walk through everything a beg
NumPy (Numerical Python) is a Python library used for numerical and scientific computing. It provides:
Support for large, multi-dimensional arrays and matrices.
A collection of mathematical functions to operate on arrays efficiently.
Vectorization: Replace slow Python loops with fast, C-based array operations.
Speed: Much faster than native Python lists.
Functionality: Advanced mathematical operations, broadcasting, linear algebra, Fourier transforms, and more.
Base for other libraries: Libraries like pandas, TensorFlow, and scikit-learn use NumPy arrays under the hood.
You can install NumPy using pip:
pip install numpy
Or via conda if you're using Anaconda:
conda install numpy
✅ Basic NumPy Example
import numpy as np
arr = np.array([1, 2, 3, 4])
print("NumPy Array:", arr)
print("Type:", type(arr))
import numpy as np
# 1D Array
arr1 = np.array([10, 20, 30])
print("1D Array:", arr1)
# 2D Array
arr2 = np.array([[1, 2], [3, 4]])
print("2D Array:\n", arr2)
📐 Array Attributes
print("Shape:", arr2.shape)
print("Data Type:", arr2.dtype)
print("Size:", arr2.size)
Reshape
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped = arr.reshape((2, 3))
print("Reshaped Array:\n", reshaped)
Indexing & Slicing
a = np.array([10, 20, 30, 40, 50])
print("Element at index 2:", a[2])
print("Sliced Array:", a[1:4])
Arithmetic Operations
arr = np.array([1, 2, 3])
print("Add 5:", arr + 5)
print("Square:", arr ** 2)
zeros
, ones
, arange
, linspace
, and MoreNumPy offers several convenient methods to create arrays for specific needs:
np.zeros()
Creates an array filled with zeros.
zero_array = np.zeros((2, 3))
print("Zeros:\n", zero_array)
np.ones()
Creates an array filled with ones.
ones_array = np.ones((3, 3))
print("Ones:\n", ones_array)
np.arange()
Creates arrays with regularly incrementing values (like range()
in Python).
arr = np.arange(0, 10, 2)
print("arange:", arr)
np.linspace()
Creates evenly spaced numbers between a start and end value.
arr = np.linspace(0, 1, 5)
print("linspace:", arr)
🔄 np.full()
, np.eye()
, np.random
# np.full
filled = np.full((2, 2), 7)
print("Full:\n", filled)
# np.eye (Identity Matrix)
identity = np.eye(3)
print("Identity Matrix:\n", identity)
# Random values
random_arr = np.random.rand(2, 3)
print("Random Array:\n", random_arr)
NumPy is your gateway to high-performance computing in Python. Mastering array creation, manipulation, and basic operations allows you to work with data efficiently, whether you're plotting graphs, running simulations, or training ML models.
Join Jugal on Peerlist!
Join amazing folks like Jugal and thousands of other people in tech.
Create ProfileJoin with Jugal’s personal invite link.
0
5
0