Kev*_*dra 13 python arrays numpy
比方说,我有一个数组
x.shape = (10,1024)
当我尝试打印 x[0].shape
x[0].shape
Run Code Online (Sandbox Code Playgroud)
它打印 1024
当我打印 x.shape[0]
x.shape[0]
Run Code Online (Sandbox Code Playgroud)
它打印 10
我知道这是一个愚蠢的问题,也许还有另一个类似的问题,但有人可以向我解释一下吗?
cs9*_*s95 15
x
是一个二维数组,也可以看作是一维数组的数组,有 10 行和 1024 列。x[0]
是第一个具有 1024 个元素的一维子数组(在 中有 10 个这样的一维子数组x
),并x[0].shape
给出该子数组的形状,它恰好是一个 1 元组 - (1024, )
。
另一方面,x.shape
是一个 2 元组,表示 的形状x
,在这种情况下是(10, 1024)
。x.shape[0]
给出该元组中的第一个元素,即10
。
这是一个带有一些较小数字的演示,希望它更容易理解。
x = np.arange(36).reshape(-1, 9)
x
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35]])
x[0]
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
x[0].shape
(9,)
x.shape
(4, 9)
x.shape[0]
4
Run Code Online (Sandbox Code Playgroud)
小智 7
x[0].shape
将给出数组第一行的长度。x.shape[0]
将给出数组中的行数。在你的情况下,它会给出输出 10。如果你输入x.shape[1]
,它会打印出列数,即 1024。如果你输入x.shape[2]
,它会给出一个错误,因为我们正在处理一个二维数组,我们已经结束了的索引。让我通过一个 3x4 维的二维零数组,通过一个简单的例子向您解释“形状”的所有用法。
import numpy as np
#This will create a 2-d array of zeroes of dimensions 3x4
x = np.zeros((3,4))
print(x)
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
#This will print the First Row of the 2-d array
x[0]
array([ 0., 0., 0., 0.])
#This will Give the Length of 1st row
x[0].shape
(4,)
#This will Give the Length of 2nd row, verified that length of row is showing same
x[1].shape
(4,)
#This will give the dimension of 2-d Array
x.shape
(3, 4)
# This will give the number of rows is 2-d array
x.shape[0]
3
# This will give the number of columns is 2-d array
x.shape[1]
3
# This will give the number of columns is 2-d array
x.shape[1]
4
# This will give an error as we have a 2-d array and we are asking value for an index
out of range
x.shape[2]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-20-4b202d084bc7> in <module>()
----> 1 x.shape[2]
IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
39453 次 |
最近记录: |