NumPy中x.shape[0]与x[0].shape的区别解析
Understanding the Difference Between
x[0].shape and x.shape[0] Hey there! Let's break this down clearly—these two expressions are asking completely different things about your NumPy array, even though they look similar.
First, recap your setup
You have a 2-dimensional NumPy array x with x.shape = (10, 1024). Think of this as a table with 10 rows and 1024 columns.
What does x[0].shape do?
x[0]accesses the first element along the array's first axis. For a 2D array, the first axis is the "row" axis, sox[0]gives you the entire first row of your table.- This first row is itself a 1-dimensional array (just a single row of 1024 values). When you call
.shapeon this 1D sub-array, you get its length:1024(or(1024,)in full NumPy tuple notation—some environments might print just the number for simplicity).
What does x.shape[0] do?
x.shapeis an attribute of the original array that returns a tuple representing the size of each axis. For your array, this tuple is(10, 1024): the first value is the number of rows, the second is the number of columns.x.shape[0]grabs the first element of this tuple, which corresponds to the length of the first axis (the total number of rows). That's why you get10.
Quick code example to see it in action
import numpy as np x = np.random.rand(10, 1024) # Create your 2D array # Get the shape of the first row (1D sub-array) print(x[0].shape) # Output: (1024,) or 1024 depending on your environment # Get the length of the first axis (number of rows) print(x.shape[0]) # Output: 10
Simplified analogy
Imagine x is a stack of 10 notebooks, each with 1024 pages:
x[0]is grabbing the first notebook—asking its shape is like counting how many pages are in that single notebook (1024).x.shape[0]is counting how many notebooks are in the entire stack (10).
内容的提问来源于stack exchange,提问作者Kevin Chandra
相关产品推荐
相关产品推荐

