How do you slice and access the i-th column of a 2D NumPy array? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you slice and access the i-th column of a 2D NumPy array?

message-square
0

Index the 2D array with arr[:, i] (using : to select all rows along axis 0 and integer i along axis 1) to obtain a zero-copy 1D view of the $i$-th column in $O(1)$ time, or use arr[:, i:i+1] (or arr[:, [i]]) when you need to preserve the 2D column-vector shape (n_rows, 1) for broadcasting or matrix multiplication.

Basic Example

import numpy as np

arr = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90],
])

# 1. Recommended: Extract the i-th column (e.g., index 1) as a 1D view (shape: (3,))
col_1 = arr[:, 1]
print(col_1, col_1.shape)
# Output: [20 50 80] (3,)

# Negative indexing accesses columns from the right (last column):
last_col = arr[:, -1]
print(last_col)
# Output: [30 60 90]

# 2. Keep 2D column-vector dimensions (shape: (3, 1)) for broadcasting or linear algebra:
col_1_2d = arr[:, 1:2]
print(col_1_2d.shape)
# Output: (3, 1)

# 3. Extract multiple non-contiguous columns (e.g., columns 0 and 2 — returns a copy):
subset = arr[:, [0, 2]]
print(subset)
# Output:
# [[10 30]
#  [40 60]
#  [70 90]]

Key Details & Edge Cases

  • arr[:, i] returns a mutable view—modifying it mutates the original array:
    • Basic slicing (arr[:, 1]) shares underlying memory with arr without copying data. Setting col_1[0] = 999 also updates arr[0, 1] to 999. Call arr[:, i].copy() if you need an independent array, or if you plan to store a small column slice from a massive array and let the large array be garbage-collected.
  • Never write arr[:][i]—that selects the $i$-th row, not the $i$-th column:
    • arr[:] evaluates first to the entire 2D array arr, so arr[:][i] is identical to arr[i] (which indexes axis 0, returning row i). Always pass both axes inside a single pair of brackets separated by a comma: arr[:, i].
  • Edge case for negative index i = -1 with arr[:, i:i+1]:
    • Using arr[:, i:i+1] works to keep 2D shape (n, 1) for all non-negative indices (0, 1, ...), but fails for i = -1 because -1 + 1 == 0, producing an empty slice arr[:, -1:0] of shape (n, 0)! For negative indices or general code, use arr[:, [i]] or arr[:, i, np.newaxis] (which safely works for both positive and negative i).
  • Selecting a range of contiguous columns (start:stop:step):
    • Slice column ranges with arr[:, 1:3] (columns 1 and 2, exclusive of 3), arr[:, ::2] (every second column), or arr[:, ::-1] (all columns reversed).
  • Memory layout performance note (C-order vs. F-order):
    • Default NumPy arrays are row-major (C-contiguous), so elements of arr[:, i] sit at strided intervals (arr.strides[0] bytes apart) in memory. Vectorized NumPy ufuncs (arr[:, i].sum(), np.mean(arr[:, i])) handle strided views natively, though copying (arr[:, i].copy()) before tight Python/Cython loops can improve CPU cache locality.

Comparison of Column Indexing Expressions on a 2D NumPy Array (shape = (M, N))

Expression Output Shape Returns View or Copy? Works for Negative i (-1)? Best Used When
arr[:, i] (Recommended) (M,) (1D) View (zero-copy) Yes (arr[:, -1]) Standard 1D column access, aggregations (arr[:, i].mean()), and in-place column updates (arr[:, i] = 0).
arr[:, i, np.newaxis] (or arr[:, None, i]) (M, 1) (2D) View (zero-copy) Yes (arr[:, -1, None]) Preserving 2D column-vector shape for row-wise broadcasting (arr - arr[:, i, None]) or np.hstack.
arr[:, i:i+1] (M, 1) (2D) View (zero-copy) No (-1:0 gives (M, 0)) Simple non-negative column slicing when you want a 2D slice without np.newaxis.
arr[:, [i]] or arr[:, [0, 2]] (M, 1) or (M, K) (2D) Copy (fancy indexing) Yes (arr[:, [-1]]) Selecting multiple arbitrary/reordered columns or safely isolating a 2D column copy.