NumPy
Reshaping
Reshape, transpose, and stack arrays.
By EZ4Code Team
reshapetransposestack
Code
import numpy as np
a = np.arange(12)
# Reshape and -1 inference
b = a.reshape(3, 4)
c = a.reshape(-1, 2) # 6 rows inferred
flat = b.flatten() # copy
ravel = b.ravel() # view when possible
# Transpose and swap axes
t = b.T
swapped = b.swapaxes(0, 1)
# Stacking
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
vstack = np.vstack([x, y]) # rows
hstack = np.hstack([x, y]) # columns
concat = np.concatenate([x, y])
print(b.shape, c.shape, vstack.shape)Explanation
reshape returns a view with the same data in a new shape, and -1 lets NumPy infer one dimension automatically. flatten copies while ravel usually returns a view, so prefer ravel when mutating. vstack and hstack concatenate along new and existing axes respectively.
More NumPy Snippets
Array Creation
Create arrays from lists and built-in constructors.
Indexing and Slicing
Slice arrays and index with boolean masks.
Broadcasting
Combine arrays of compatible shapes without copying.
Math Operations
Apply element-wise math and reductions.
Linear Algebra
Solve systems, factorize, and compute eigenvalues.
Random Numbers
Sample from distributions with a Generator.