我怎么能总是让numpy.ndarray.shape返回一个两值元组?

时间:2015-07-29 23:58:21

标签: python arrays numpy matrix shape

我试图从2D矩阵中获取(nRows,nCols)的值但是当它是单行时(即x = np.array([1,2,3,4])),x.shape将返回(4,)所以我的声明(nRows,nCols)= x.shape返回“ValueError:需要多于1个值来解包”

有关如何使此声明更具适应性的任何建议?这是一个在许多程序中使用的函数,应该适用于单行和多行matices。谢谢!

2 个答案:

答案 0 :(得分:1)

如果您的功能使用

 (nRows, nCols) = x.shape 

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

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

通常的做法是重塑x(根据需要),因此它至少有一行。换句话说,将形状从(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问题之一,要求将1d数组视为2d。

答案 1 :(得分:0)

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

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