Adding data to an existing NumPy array requires understanding that NumPy arrays have a fixed size in memory. Operations like numpy.append() and numpy.concatenate() do not modify the array in place; instead, they allocate and return a new array.
Axis & Dimension Rules: When appending along an axis (e.g., adding rows with axis=0 or columns with axis=1), all dimensions other than the target axis must match exactly. To explore multidimensional array geometries, review ndarray attributes and shape. For allocating new buffers in advance, see numpy.zeros() and numpy.empty().
Unlike Python standard lists that dynamically resize using list.append() in $\mathcal{O}(1)$ amortized time, a NumPy ndarray occupies a continuous memory block of fixed length. When you execute np.append():
axis parameter is provided, both arrays are completely flattened into a 1D array before joining.# Default append behavior: complete flatteningimport numpy as npa = np.array([[1, 2], [3, 4]])b = np.array([[5, 6]])flat_res = np.append(a, b)print("Flattened Result: ", flat_res)print("Result Shape: ", flat_res.shape)Terminal Output:
Flattened Result: [1 2 3 4 5 6]Result Shape: (6,)To preserve a 2D matrix structure and insert a new row, pass axis=0. The array to be added must match the column count of the target array and must share the exact same number of dimensions (2D):
# Appending rows along axis 0import numpy as npnpr = np.array([ [0, 1, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9]])# Notice the double square brackets [[...]] to preserve a 2D shape (1, 4)new_row = [[10, 11, 12, 13]]res_rows = np.append(npr, new_row, axis=0)print("Appended Along Axis 0 (Rows):\n", res_rows)print("New Shape:", res_rows.shape)Terminal Output:
Appended Along Axis 0 (Rows): [[ 0 1 2 4] [ 3 4 5 6] [ 6 7 8 9] [10 11 12 13]]New Shape: (4, 4)To attach new columns horizontally, specify axis=1. The incoming array must have the identical row count as the target array:
# Appending columns along axis 1import numpy as npnpr = np.array([ [0, 1, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9]])cols = np.array([ [10, 11, 12, 13], [21, 22, 23, 24], [31, 32, 34, 35]])res_cols = np.append(npr, cols, axis=1)print("Appended Along Axis 1 (Columns):\n", res_cols)print("New Shape:", res_cols.shape)Terminal Output:
Appended Along Axis 1 (Columns): [[ 0 1 2 4 10 11 12 13] [ 3 4 5 6 21 22 23 24] [ 6 7 8 9 31 32 34 35]]New Shape: (3, 8)The most frequent error when adding data to a 2D array is passing a 1D vector (single bracket [...]) instead of a 2D matrix (double brackets [[...]]):
Here is how to identify and resolve this error using reshape or slicing:
# Resolving dimension mismatch errorsimport numpy as npbase = np.zeros((3, 4))row_1d = np.array([1, 2, 3, 4]) # Shape (4,) -> Causes ValueError with axis=0# Fix 1: Reshape to 2D (1, 4)safe_row1 = row_1d.reshape(1, -1)# Fix 2: Expand dimensions via np.newaxissafe_row2 = row_1d[np.newaxis, :]res = np.append(base, safe_row1, axis=0)print("Successfully appended row. Shape:", res.shape)While np.append() works well for simple additions, production code commonly relies on np.concatenate(), np.vstack(), or np.hstack() for speed and flexibility:
| Method | Input Format | Axis Behavior | Best Used For |
|---|---|---|---|
np.append(arr, values, axis=None) | Two arrays / lists | Flattens if axis is omitted | Quick scalar or single-array additions |
np.concatenate([a, b, c], axis=0) | Tuple / list of arrays | Explicit axis required | Joining multiple arrays in a single allocation |
np.vstack([a, b]) | Tuple / list of arrays | Stacks vertically (row-wise) | Stacking 1D vectors as rows into a 2D matrix |
np.hstack([a, b]) | Tuple / list of arrays | Stacks horizontally (col-wise) | Joining feature columns side-by-side |
Repeatedly appending in a loop (e.g., for item in stream: arr = np.append(arr, item)) is an anti-pattern with quadratic $\mathcal{O}(N^2)$ memory overhead. Instead, collect items in a Python list and convert once, or preallocate with np.zeros():
# High-performance batch allocation recipeimport numpy as np# Approach A: Preallocation when final size is knowntotal_rows = 1000buffer = np.zeros((total_rows, 4), dtype=float)for i in range(total_rows): buffer[i] = [1.0, 2.0, 3.0, 4.0]# Approach B: List accumulator when total size is dynamicaccumulator = []for i in range(5): accumulator.append([i, i * 2, i * 3])final_matrix = np.array(accumulator)print("Built Array in a single allocation:\n", final_matrix)Test all array appending operations, verify dimension alignments, and run self-validating unit tests in our companion notebook:
Launch the practice notebook directly in Google Colab to run live experiments or download the .ipynb file from GitHub:
np.append() returns a newly created copy with the appended values. You must assign the output back to a variable. axis parameter (i.e. default axis=None), NumPy flattens both the original array and the values being added into a single 1D vector. Always specify axis=0 for rows or axis=1 for columns. Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.