Unlock NumPy: Comprehensive Guide to Array Iteration, Reshaping, and Advanced Operations
Explore a thorough NumPy tutorial covering array iteration with nditer, reshaping functions like reshape, flat, and flatten, dimension modifications, transposition, axis swapping, broadcasting, stacking, concatenation, splitting, element manipulation, string utilities, arithmetic, statistical, sorting, searching, and file I/O, all illustrated with clear Python code examples.
01 Array Iteration
NumPy provides the multi‑dimensional iterator numpy.nditer which follows the standard Python iterator protocol, allowing element‑wise traversal of an array.
import numpy as np
a = np.arange(0, 60, 5)
a = a.reshape(3, 4)
print(a)
for x in np.nditer(a):
print(x)If two arrays are broadcastable, np.nditer can iterate over them simultaneously, broadcasting the smaller array to the shape of the larger one.
import numpy as np
a = np.arange(0, 60, 5).reshape(3, 4)
print(a)
b = np.array([1, 2, 3, 4], dtype=int)
print(b)
for x, y in np.nditer([a, b]):
print(x, y)02 Array Shape‑Modification Functions
ndarray.reshape
Returns a new view of the array with a different shape without changing its data.
import numpy as np
a = np.arange(8)
print(a)
b = a.reshape(4, 2)
print(b)ndarray.flat
Provides a 1‑D iterator over the array, similar to Python's built‑in iterator.
import numpy as np
a = np.arange(0, 16, 2).reshape(2, 4)
print(a)
print(list(a.flat))ndarray.flatten
Returns a copy of the array collapsed into one dimension. The optional order argument can be 'C', 'F', 'A', or 'K'.
import numpy as np
a = np.arange(8).reshape(2, 4)
print(a)
print(a.flatten())
print(a.flatten(order='F'))03 Array Transposition Functions
numpy.transpose
Permutes the axes of an array, returning a view when possible.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a)
b = np.transpose(a)
print(b)
print(b.shape)
# custom axes order
c = np.transpose(a, (1, 0, 2))
print(c)ndarray.T
Convenient shortcut for numpy.transpose on a 2‑D array.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a)
print(a.T)numpy.swapaxes
Swaps two axes of an array.
import numpy as np
a = np.arange(8).reshape(2, 2, 2)
print(a)
print(np.swapaxes(a, 2, 0))numpy.rollaxis
Rolls the specified axis backwards until it reaches a given position.
import numpy as np
a = np.arange(8).reshape(2, 2, 2)
print(a)
print(np.rollaxis(a, 2))
print(np.rollaxis(a, 2, 1))04 Array Broadcasting and Dimension‑Adding Functions
numpy.broadcast_to
Broadcasts an array to a new shape, returning a read‑only view.
import numpy as np
a = np.arange(4).reshape(1, 4)
print(a)
print(np.broadcast_to(a, (4, 4)))numpy.expand_dims
Inserts a new axis at the specified position.
import numpy as np
x = np.array([[1, 2], [3, 4]])
print(x)
y = np.expand_dims(x, axis=0)
print(y)
y = np.expand_dims(x, axis=1)
print(y)numpy.squeeze
Removes axes of length one from the shape of an array.
import numpy as np
x = np.arange(9).reshape(1, 3, 3)
print(x)
y = np.squeeze(x)
print(y)05 Array Stacking and Concatenation
NumPy provides four main functions for joining arrays: concatenate, stack, hstack, and vstack.
numpy.stack
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
print(np.stack((a,b), 0))
print(np.stack((a,b), 1))numpy.hstack
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
print('Horizontal stack:')
print(np.hstack((a, b)))numpy.vstack
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
print('Vertical stack:')
print(np.vstack((a, b)))numpy.concatenate
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
print(np.concatenate((a, b)))
print(np.concatenate((a, b), axis=1))06 Array Splitting Functions
Key splitting utilities are split, hsplit, and vsplit.
numpy.split
import numpy as np
a = np.arange(9)
print(a)
print('Three equal parts:')
print(np.split(a, 3))
print('Split at indices 4 and 7:')
print(np.split(a, [4, 7]))numpy.hsplit
import numpy as np
a = np.arange(16).reshape(4,4)
print(a)
print('Horizontal split:')
print(np.hsplit(a, 2))numpy.vsplit
import numpy as np
a = np.arange(16).reshape(4,4)
print(a)
print('Vertical split:')
print(np.vsplit(a, 2))07 Array Element Operations
Functions include resize, append, insert, delete, and unique.
numpy.resize
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)
print(a.shape)
print(np.resize(a, (3,2)))
print(np.resize(a, (3,3)))
print(np.resize(a, (2,2)))numpy.append
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(np.append(a, [[7,8,9]], axis=0))
print(np.append(a, [[5,5,5],[7,8,9]], axis=1))numpy.insert
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(np.insert(a, 3, [11,12]))
print(np.insert(a, 1, [11], axis=0))
print(np.insert(a, 1, [11], axis=1))numpy.delete
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(np.delete(a, 5))
print(np.delete(a, 1, axis=1))numpy.unique
import numpy as np
a = np.array([5,2,6,2,7,5,6,8,2,9])
print(np.unique(a))
print(np.unique(a, return_index=True))
print(np.unique(a, return_inverse=True))
print(np.unique(a, return_counts=True))08 NumPy String Functions
Vectorised string operations are available via numpy.char.
import numpy as np
print(np.char.add(['hello'], [' xyz']))
print(np.char.multiply('Hello ', 3))
print(np.char.center('hello', 20, fillchar='*'))
print(np.char.capitalize('hello world'))
print(np.char.title('hello how are you?'))
print(np.char.lower(['HELLO','WORLD']))
print(np.char.upper('hello'))
print(np.char.split('hello how are you?'))
print(np.char.split('YiibaiPoint,Hyderabad,Telangana', sep=','))
print(np.char.strip('ashok arora', 'a'))
print(np.char.join(':', 'dmy'))
print(np.char.replace('He is a good boy', 'is', 'was'))09 NumPy Arithmetic Functions
Includes trigonometric, rounding, and basic arithmetic utilities.
import numpy as np
a = np.array([0,30,45,60,90])
print(np.sin(a*np.pi/180))
print(np.cos(a*np.pi/180))
print(np.tan(a*np.pi/180))10 Sorting, Searching and Counting
import numpy as np
a = np.array([[3,7,3,1],[9,7,8,7]])
print(np.sort(a))
print(np.argsort(a))
print(np.argmax(a))
print(np.argmin(a))
print(np.nonzero(a))
print(np.where(a > 3))11 IO File Operations
import numpy as np
a = np.array([1,2,3,4,5])
np.save('outfile', a)
b = np.load('outfile.npy')
print(b)
np.savetxt('out.txt', a)
c = np.loadtxt('out.txt')
print(c)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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
