NumPy, short for Numerical Python, is the cornerstone of scientific computing in Python. While the basics of NumPy (like array creation and simple operations) are widely used, advanced NumPy functionalities enable high-performance operations on large datasets, broadcasting, linear algebra, memory efficiency, and integration with compiled languages. This guide explores those powerful features in-depth, making it essential for numerical analysts, data scientists, and machine learning practitioners.
Every NumPy array is an instance of the ndarray class. Internally, it consists of:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape:", arr.shape)
print("Strides:", arr.strides)
print("Item size:", arr.itemsize)
print("Total bytes:", arr.nbytes)
x = np.array([10, 20, 30, 40, 50])
mask = x > 25
print(x[mask])
x = np.array([5, 10, 15, 20, 25])
indices = [1, 3]
print(x[indices])
arr = np.arange(16).reshape(4, 4)
print(arr[[1, 3], [2, 0]])
x = np.array([1, 2, 3, 4, 5])
x[x > 3] = 99
print(x)
Broadcasting allows NumPy to perform arithmetic on arrays of different shapes by expanding the smaller array implicitly.
a = np.array([1, 2, 3])
b = np.array([[10], [20], [30]])
print(a + b)
x = np.array([1, 2, 3])
y = x[:, np.newaxis] # Adds a new axis
print(x.shape, y.shape)
arr = np.arange(12)
reshaped = arr.reshape((3, 4))
print("Reshaped:\n", reshaped)
arr.resize((2, 6))
print("Resized:\n", arr)
arr = np.array([[1, 2], [3, 4]])
print(arr.flatten()) # Returns a copy
print(arr.ravel()) # Returns a view
a = np.array([1, 2])
b = np.array([3, 4])
print(np.stack((a, b), axis=0))
print(np.hstack((a, b)))
print(np.vstack((a, b)))
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(np.dot(A, B))
print(A @ B) # Python 3.5+ operator
from numpy.linalg import inv, det
matrix = np.array([[4, 7], [2, 6]])
print("Inverse:\n", inv(matrix))
print("Determinant:", det(matrix))
from numpy.linalg import eig
vals, vecs = eig(matrix)
print("Eigenvalues:", vals)
print("Eigenvectors:\n", vecs)
np.random.seed(0)
rand_arr = np.random.rand(3, 3)
print(rand_arr)
normal_arr = np.random.normal(loc=0.0, scale=1.0, size=(2, 3))
print(normal_arr)
int_arr = np.random.randint(0, 10, size=(3, 3))
print(int_arr)
arr = np.arange(10)
np.random.shuffle(arr)
print(arr)
perm = np.random.permutation(10)
print(perm)
a = np.array([1, 2, 3])
b = a.view()
b[0] = 100
print("Original:", a)
x = np.arange(16).reshape(4, 4)
print(x[::2, ::2]) # Strided slicing
x = np.arange(1_000_000)
y = np.arange(1_000_000)
# Fast vectorized addition
result = x + y
x = np.array([1, 2, 3, 4])
y = np.where(x > 2, x * 10, x)
print(y)
import numexpr as ne
a = np.arange(1e6)
b = np.arange(1e6)
c = ne.evaluate("a + b * 2")
print(c)
import numpy.ma as ma
data = np.array([1, 2, 999, 4])
masked_data = ma.masked_equal(data, 999)
print(masked_data)
structured = np.array([(1, 'A'), (2, 'B')],
dtype=[('id', 'i4'), ('label', 'U1')])
print(structured['id'])
print(structured['label'])
x = np.array([1, 2, 3])
print(np.exp(x))
print(np.sqrt(x))
def custom_op(x, y):
return x**2 + y
vec_func = np.frompyfunc(custom_op, 2, 1)
result = vec_func([1, 2, 3], [4, 5, 6])
print(result)
matrix = np.array([[1], [2], [3]])
vector = np.array([10, 20, 30])
result = matrix + vector
print(result)
from PIL import Image
img = Image.open("sample.jpg").convert("L")
img_np = np.array(img)
print(img_np.shape)
# Apply thresholding
img_np[img_np < 128] = 0
img_np[img_np >= 128] = 255
prices = np.array([100, 101, 102, 98, 105])
returns = np.diff(prices) / prices[:-1]
print("Returns:", returns)
steps = np.random.choice([-1, 1], size=1000)
position = np.cumsum(steps)
Advanced NumPy capabilities go far beyond simple array creation and slicing. Mastering these features unlocks high-performance numerical computing in Python. From broadcasting and advanced indexing to structured arrays, masked operations, linear algebra, and random simulations, NumPy enables efficient and scalable data processing. It's the backbone of many scientific computing and machine learning tasks, forming the core of the Python data ecosystem. Practicing these advanced techniques will prepare you for real-world numerical analysis challenges with large datasets and performance constraints.
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