【问题标题】:What does .shape[] do in "for i in range(Y.shape[0])"?.shape[] 在“for i in range(Y.shape[0])”中做了什么?
【发布时间】:2012-04-29 07:49:35
【问题描述】:

我正在尝试逐行分解程序。 Y 是一个数据矩阵,但我找不到任何关于 .shape[0] 究竟做了什么的具体数据。

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

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

【问题讨论】:

标签: python numpy matplotlib scipy


【解决方案1】:

numpy 数组的shape 属性返回数组的维度。如果Y 具有n 行和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

【讨论】:

    【解决方案2】:

    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 还有更多 例子。

    【讨论】:

    【解决方案3】:

    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
    

    给出列数

    【讨论】:

      【解决方案4】:

      在 Python 中,shape() 在 pandas 中用于给出行数/列数:

      行数由下式给出:

      train = pd.read_csv('fine_name') //load the data
      train.shape[0]
      

      列数由

      给出
      train.shape[1]
      

      【讨论】:

        【解决方案5】:

        在 python 中,假设你已经在某个变量 train 中加载了数据:

        train = pandas.read_csv('file_name')
        >>> train
        train([[ 1.,  2.,  3.],
                [ 5.,  1.,  2.]],)
        

        我想检查“文件名”的尺寸。我已将文件存储在火车中

        >>>train.shape
        (2,3)
        >>>train.shape[0]              # will display number of rows
        2
        >>>train.shape[1]              # will display number of columns
        3
        

        【讨论】:

          【解决方案6】:

          shape() 由具有两个参数行和列的数组组成。

          如果您搜索shape[0],那么它会为您提供行数。 shape[1] 会给你列数。

          【讨论】:

            猜你喜欢
            • 2021-05-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-02-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-07-27
            相关资源
            最近更新 更多