NumPy is the foundational library for numerical computing in Python. At its core is the ndarray, or N-dimensional array, which provides efficient storage and operations for homogeneous numerical data. Unlike Python lists, which can hold elements of different types and incur memory and performance overhead, NumPy arrays are typed, contiguous, and optimized for vectorized operations.
An ndarray is a grid of values, all of the same type, indexed by a tuple of non-negative integers. The number of dimensions is the rank of the array; the shape is a tuple giving the size of each dimension.
import numpy as np
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
Here, arr1 is a 1-dimensional array, and arr2 is 2-dimensional.
arr_int = np.array([1, 2, 3], dtype=np.int64)
arr_float = np.array([1, 2, 3], dtype=np.float32)
zeros = np.zeros((3, 4))
ones = np.ones((2, 5))
identity = np.eye(4)
full = np.full((3, 3), 7)
random_arr = np.random.random((2, 2))
NumPy allows inspecting key properties of arrays:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.ndim) # Number of dimensions
print(arr.shape) # Tuple of array dimensions
print(arr.size) # Total number of elements
print(arr.dtype) # Data type of elements
print(arr.itemsize) # Bytes per element
print(arr.nbytes) # Total bytes consumed
arr = np.array([10, 20, 30, 40, 50])
print(arr[0], arr[3])
print(arr[-1])
mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(mat[0, 1])
print(mat[2, 2])
sub = mat[0:2, 1:3]
sub[0, 0] = 99
print(mat)
Note: slicing returns a view, not a copy.
Integer array indexing and boolean masking are powerful features.
row_indices = [0, 2]
col_indices = [1, 2]
print(mat[row_indices, col_indices])
mask = mat > 5
print(mat[mask])
flat = np.arange(12)
reshaped = flat.reshape((3, 4))
print(reshaped)
reshaped.flatten()
reshaped.ravel()
reshaped.shape = (2, 6)
print(reshaped)
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a * 10)
print(a + 100)
print(np.sin(a))
print(np.exp(a))
print(np.sqrt(a))
data = np.array([[1, 2, 3], [4, 5, 6]])
print(data.sum())
print(data.mean(axis=0))
print(data.max(axis=1))
NumPy supports operations between arrays of different shapes by broadcasting:
arr3 = np.array([[1], [2], [3]])
print(arr3 + np.array([10, 20, 30]))
h = np.hstack((a, b))
v = np.vstack((a, b))
print(np.concatenate((h, h), axis=0))
print(np.split(h, 3))
a = np.arange(5)
b = a.view()
c = a.copy()
b[0] = 99
print(a)
print(c)
Vectorized operations with NumPy are orders of magnitude faster than equivalent Python loops.
import time
size = 10_000_000
py_list = list(range(size))
np_arr = np.arange(size)
start = time.time()
result1 = [x * 2 for x in py_list]
end = time.time()
print("Python list time:", end - start)
start = time.time()
result2 = np_arr * 2
end = time.time()
print("NumPy array time:", end - start)
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A @ B)
print(np.linalg.inv(A))
print(np.linalg.eig(A))
from scipy import signal
t = np.linspace(0, 1, 1000)
sig = np.sin(2 * np.pi * 10 * t)
filtered = signal.savgol_filter(sig, 51, 3)
from PIL import Image
img = Image.open('example.jpg')
arr = np.array(img)
print(arr.shape)
arr_gray = arr.mean(axis=2).astype(np.uint8)
import pandas as pd
df = pd.DataFrame(arr, columns=['R', 'G', 'B'])
print(df.head())
from sklearn.decomposition import PCA
X = np.random.rand(100, 5)
pca = PCA(n_components=2)
X2 = pca.fit_transform(X)
print(X2.shape)
def sliding_window(arr, window_size, step=1):
shape = ((arr.size - window_size)//step + 1, window_size)
strides = (arr.strides[0]*step, arr.strides[0])
return np.lib.stride_tricks.as_strided(arr, shape=shape, strides=strides)
win = sliding_window(np.arange(10), 3, 2)
print(win)
large = np.memmap('large.dat', dtype='float32', mode='w+', shape=(1000, 1000))
NumPy arrays form a powerful backbone for scientific and high-performance computing in Python. From basic creation and indexing to advanced matrix operations, NumPy offers clarity, speed, and functionality. When used properly, it enables writing clean, efficient, and highly performant code.
In this guide, we explored array creation, inspection, slicing, reshaping, arithmetic, advanced indexing, performance benchmarks, real-world use cases, and best practices. With frequent use and deeper exploration, NumPy becomes an indispensable tool in any data-driven or numerical Python development workflow.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved