【问题标题】:How can I always have numpy.ndarray.shape return a two valued tuple?我怎样才能让 numpy.ndarray.shape 返回一个二值元组?
【发布时间】:2015-07-30 11:11:21
【问题描述】:

我试图从 2D 矩阵中获取 (nRows, nCols) 的值,但是当它是单行时(即 x = np.array([1, 2, 3, 4])),x.shape将返回 (4,),因此我的 (nRows, nCols) = x.shape 语句返回“ValueError: need more than 1 value to unpack”

关于如何使此语句更具适应性的任何建议?它适用于许多程序中使用的功能,并且应该与单行和多行配合使用。谢谢!

【问题讨论】:

    标签: python arrays numpy matrix shape


    【解决方案1】:

    您可以创建一个返回行和列元组的函数,如下所示:

    def rowsCols(a):
        if len(a.shape) > 1:
            rows = a.shape[0]
            cols = a.shape[1]
        else:
            rows = a.shape[0]
            cols = 0
        return (rows, cols)
    

    其中a 是您输入到函数的数组。下面是一个使用函数的例子:

    import numpy as np
    
    x = np.array([1,2,3])
    
    y = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
    
    def rowsCols(a):
        if len(a.shape) > 1:
            rows = a.shape[0]
            cols = a.shape[1]
        else:
            rows = a.shape[0]
            cols = 0
        return (rows, cols)
    
    (nRows, nCols) = rowsCols(x)
    
    print('rows {} and columns {}'.format(nRows, nCols))
    
    (nRows, nCols) = rowsCols(y)
    
    print('rows {} and columns {}'.format(nRows, nCols))
    

    这将打印rows 3 and columns 0,然后打印rows 4 and columns 3。或者,您可以使用atleast_2d 函数来获得更简洁的方法:

    (r, c) = np.atleast_2d(x).shape
    
    print('rows {}, cols {}'.format(r, c))
    
    (r, c) = np.atleast_2d(y).shape
    
    print('rows {}, cols {}'.format(r, c))
    

    打印rows 1, cols 3rows 4, cols 3

    【讨论】:

      【解决方案2】:

      如果你的函数使用

       (nRows, nCols) = x.shape 
      

      它可能还会在 x 上建立索引或迭代,假设它有 nRows 行,例如

       x[0,:]
       for row in x:
          # do something with the row
      

      通常的做法是重塑x(根据需要),使其至少有 1 行。也就是说,将形状从(n,) 更改为(1,n)

       x = np.atleast_2d(x)
      

      做得很好。在函数内部,对x 的这种更改不会影响外部的x。这样,您可以在整个函数中将x 视为 2d,而不是不断查看它是否是 1d v 2d。

      Python: How can I force 1-element NumPy arrays to be two-dimensional?

      是之前许多关于将一维数组视为二维的 SO 问题之一。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-13
        • 1970-01-01
        • 2020-12-19
        • 1970-01-01
        • 2015-12-19
        • 1970-01-01
        • 1970-01-01
        • 2015-04-13
        相关资源
        最近更新 更多