"在“for i in range(Y.shape[0])”中,.shape[]的作用是什么?"

2024-04-18 13:41:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图逐行分解一个程序。Y是一个数据矩阵,但是我找不到关于.shape[0]的具体数据。

for i in range(Y.shape[0]):
    if Y[i] == -1:

这个程序使用numpy、scipy、matplotlib.pyplot和cvxopt。


Tags: 数据in程序numpyforifmatplotlibrange
3条回答

shape是一个元组,它指示数组中的维数。因此,在您的例子中,由于Y.shape[0]的索引值是0,您将沿着数组的第一个维度工作。

http://www.scipy.org/Tentative_NumPy_Tutorial#head-62ef2d3c0a5b4b7d6fdc48e4a60fe48b1ffe5006

 An array has a shape given by the number of elements along each axis:
 >>> a = floor(10*random.random((3,4)))

 >>> a
 array([[ 7.,  5.,  9.,  3.],
        [ 7.,  2.,  7.,  8.],
        [ 6.,  8.,  3.,  2.]])

 >>> a.shape
 (3, 4)

还有http://www.scipy.org/Numpy_Example_List#shape还有一些 例子。

shape是一个元组,它给出数组的维数。。

>>> c = arange(20).reshape(5,4)
>>> c
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

c.shape[0] 
5

给出行数

c.shape[1] 
4

给出列数

numpy数组的shape属性返回数组的维度。如果Yn行和m列,那么Y.shape就是(n,m)。所以Y.shape[0]就是n

In [46]: Y = np.arange(12).reshape(3,4)

In [47]: Y
Out[47]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [48]: Y.shape
Out[48]: (3, 4)

In [49]: Y.shape[0]
Out[49]: 3

相关问题 更多 >