Comprehensive Guide to NumPy Array Operations and Functions
This article provides a detailed tutorial on NumPy array manipulation in Python, covering iteration with np.nditer, reshaping, flattening, transposition, axis swapping, broadcasting, stacking, concatenation, splitting, resizing, appending, inserting, deleting, unique element extraction, string utilities, arithmetic, statistical analysis, sorting, searching, and file I/O, each illustrated with concise code examples.
NumPy offers the numpy.nditer iterator for efficient multi‑dimensional array traversal, allowing element‑wise access using Python's iterator protocol.
Reshaping arrays without changing data can be done with ndarray.reshape, while ndarray.flat and ndarray.flatten provide one‑dimensional views or copies of the data.
Array dimension manipulation functions include numpy.broadcast_to for broadcasting, numpy.expand_dims for adding new axes, and numpy.squeeze for removing singleton dimensions.
Reordering axes is possible with numpy.transpose, the ndarray.T attribute, numpy.swapaxes, and numpy.rollaxis, each demonstrated with example arrays.
Combining arrays can be performed using numpy.stack, numpy.hstack, numpy.vstack, and numpy.concatenate, with optional axis arguments to control the direction of concatenation.
Splitting arrays into sub‑arrays is supported by numpy.split, numpy.hsplit, and numpy.vsplit, which divide arrays horizontally or vertically based on size or index positions.
Array element manipulation functions include numpy.resize (changing shape with possible repetition), numpy.append (adding values at the end), numpy.insert (inserting values at a given index), numpy.delete (removing elements), and numpy.unique (extracting distinct elements with optional indices, inverse mapping, and counts).
Vectorized string operations are available via the numpy.char module, offering functions such as add, multiply, center, capitalize, title, lower, upper, split, strip, join, replace, encode, and decode.
Arithmetic utilities include numpy.reciprocal, numpy.power, and numpy.mod for element‑wise reciprocal, exponentiation, and modulus operations.
Statistical functions such as numpy.amin, numpy.amax, numpy.ptp, numpy.percentile, numpy.median, numpy.mean, numpy.average, numpy.std, and numpy.var provide min/max, range, percentiles, median, mean, weighted average, standard deviation, and variance calculations.
Sorting and searching utilities include numpy.sort, numpy.argsort, numpy.lexsort, numpy.argmax, numpy.argmin, numpy.nonzero, numpy.where, and numpy.extract, enabling ordered outputs and index retrieval based on conditions.
File I/O for arrays is handled by numpy.save / numpy.load for binary .npy files and numpy.savetxt / numpy.loadtxt for plain‑text representations.
Example code snippets:
import numpy as np
a = np.arange(0, 60, 5).reshape(3, 4)
for x in np.nditer(a):
print(x)
b = a.reshape(4, 2)
print(b)
c = np.stack((a, a), axis=0)
print(c)
split_arrays = np.split(np.arange(9), 3)
print(split_arrays)
unique_vals, indices = np.unique(np.array([5,2,6,2,7,5]), return_index=True)
print(unique_vals, indices)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
