NumPy数组切片维度疑问:为何两种切片分别返回列与行?
Hey there! Let's break down your NumPy slicing questions clearly, step by step.
It’s not a fixed answer—it all depends on how you structure your slice, since NumPy operates around axes (axis 0 = rows, axis 1 = columns for 2D arrays):
- If you slice only along axis 0 (e.g.,
x[1:3]), you’ll get a subset of rows. - If you slice only along axis 1 (e.g.,
x[:, 1:3]), you’ll get a subset of columns. - The key detail is whether your slice preserves the original array’s dimensions—this is exactly what’s happening in your second question.
Let’s start by re-creating your setup to make things concrete:
import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
Case a: z = x[0:4:1,0:1:1]
Here, you’re using slice ranges on both axes (0:4:1 for rows, 0:1:1 for columns). Even when a slice range only includes one element (like 0:1:1 for the first column), NumPy preserves the original axis’s dimension.
The result is a 2D array with shape (4, 1)—which looks like a column vector:
[[0] [3] [6] [9]]
You can confirm this with print(z.shape), which outputs (4, 1).
Case b: z = x[0:4 ,0]
Here, you use a slice range on axis 0, but a single index (0) on axis 1. When you index a single position along an axis, NumPy automatically "squeezes" that axis out of the result—reducing the array’s dimensionality by 1.
The result is a 1D array with shape (4,), which looks like a row vector:
[0 3 6 9]
Check with print(z.shape) and you’ll see (4,).
Quick tip: How to get a column vector from case b?
If you want to keep the 2D structure when selecting a single column, you have a few options:
- Use slice syntax for the column:
x[:, 0:1](same logic as case a) - Add a new axis explicitly:
x[:, 0, np.newaxis] - Use list indexing:
x[:, [0]](list indexes preserve dimension even for single elements)
内容的提问来源于stack exchange,提问作者Daniel Garcia De Cceres Herran

