【问题标题】:Why does the shape of a 1D array not show the number of rows as 1?为什么一维数组的形状不显示行数为 1?
【发布时间】:2017-01-30 08:54:13
【问题描述】:

我知道 numpy 数组有一个名为 shape 的方法,它返回 [No.of rows, No.of columns],shape[0] 给出行数,shape[1] 给出列数。

a = numpy.array([[1,2,3,4], [2,3,4,5]])
a.shape
>> [2,4]
a.shape[0]
>> 2
a.shape[1]
>> 4

但是,如果我的数组只有一行,那么它会返回 [No.of columns, ]。并且 shape[1] 将超出索引。例如

a = numpy.array([1,2,3,4])
a.shape
>> [4,]
a.shape[0]
>> 4    //this is the number of column
a.shape[1]
>> Error out of index

如果数组可能只有一行,我如何获取 numpy 数组的行数?

谢谢

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    rowscolumns 的概念适用于二维数组。但是,数组numpy.array([1,2,3,4]) 是一维数组,因此只有一维,因此shape 正确地返回了一个单值可迭代对象。

    对于同一数组的 2D 版本,请考虑以下情况:

    >>> a = numpy.array([[1,2,3,4]]) # notice the extra square braces
    >>> a.shape
    (1, 4)
    

    【讨论】:

    • @YichuanWang 如果您从一维数组 (a_1d = numpy.array([1,2,3,4])) 开始,您始终可以将其转换为二维数组,例如 a_2d = a_1d[None, :]
    【解决方案2】:

    然后将其转换为二维数组,这可能不是每次都可以选择的 - 可以检查 shape 返回的元组的 len(),或者只检查索引错误:

    import numpy
    
    a = numpy.array([1,2,3,4])
    print(a.shape)
    # (4,)
    print(a.shape[0])
    try:
        print(a.shape[1])
    except IndexError:
        print("only 1 column")
    

    或者,如果您知道您将只有 1 或 2 维形状,您可以尝试将其分配给一个变量以供以后使用(或返回或您拥有什么):

    try:
        shape = (a.shape[0], a.shape[1])
    except IndexError:
        shape = (1, a.shape[0])
    
    print(shape)
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2021-06-03
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 2017-08-28
      • 2018-04-06
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多