繁体   English   中英

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

[英]How can I always have numpy.ndarray.shape return a two valued tuple?

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

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

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

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

如果您的函数使用

 (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:如何强制 1 元素 NumPy 数组为二维数组?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM