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 witharrwithout copying data. Settingcol_1[0] = 999also updatesarr[0, 1]to999. Callarr[:, 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.
- Basic slicing (
- Never write
arr[:][i]—that selects the $i$-th row, not the $i$-th column:arr[:]evaluates first to the entire 2D arrayarr, soarr[:][i]is identical toarr[i](which indexes axis0, returning rowi). Always pass both axes inside a single pair of brackets separated by a comma:arr[:, i].
- Edge case for negative index
i = -1witharr[:, i:i+1]:- Using
arr[:, i:i+1]works to keep 2D shape(n, 1)for all non-negative indices (0, 1, ...), but fails fori = -1because-1 + 1 == 0, producing an empty slicearr[:, -1:0]of shape(n, 0)! For negative indices or general code, usearr[:, [i]]orarr[:, i, np.newaxis](which safely works for both positive and negativei).
- Using
- Selecting a range of contiguous columns (
start:stop:step):- Slice column ranges with
arr[:, 1:3](columns1and2, exclusive of3),arr[:, ::2](every second column), orarr[:, ::-1](all columns reversed).
- Slice column ranges with
- Memory layout performance note (
C-order vs.F-order):- Default NumPy arrays are row-major (
C-contiguous), so elements ofarr[:, 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.
- Default NumPy arrays are row-major (
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. |
You must log in or register to comment.
