[英]How can I always have numpy.ndarray.shape return a two valued tuple?
I'm trying to get the values of (nRows, nCols) from a 2D Matrix but when it's a single row (ie x = np.array([1, 2, 3, 4])), x.shape will return (4,) and so my statement of (nRows, nCols) = x.shape returns "ValueError: need more than 1 value to unpack"我正在尝试从 2D 矩阵中获取 (nRows, nCols) 的值,但是当它是单行时(即 x = np.array([1, 2, 3, 4])),x.shape 将返回( 4,) 所以我的 (nRows, nCols) = x.shape 语句返回“ValueError: 需要 1 个以上的值来解包”
Any suggestions on how I can make this statement more adaptable?关于如何使此声明更具适应性的任何建议? It's for a function that is used in many programs and should work with both single row and multi-row matices.
它用于在许多程序中使用的函数,并且应该与单行和多行 matices 一起使用。 Thanks!
谢谢!
You could create a function that returns a tuple of rows and columns like this:您可以创建一个函数,该函数返回如下所示的行和列元组:
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)
where a
is the array you input to the function.其中
a
是您输入到函数的数组。 Here's an example of using the function:以下是使用该函数的示例:
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))
This prints rows 3 and columns 0
then rows 4 and columns 3
.这将打印第
rows 3 and columns 0
然后打印第rows 4 and columns 3
。 Alternatively, you can use the atleast_2d
function for a more concise approach:或者,您可以使用
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))
Which prints rows 1, cols 3
and rows 4, cols 3
.它打印
rows 1, cols 3
和rows 4, cols 3
。
If your function uses如果您的函数使用
(nRows, nCols) = x.shape
it probably also indexes or iterates on x
with the assumption that it has nRows
rows, eg它也可能在
x
上索引或迭代,假设它有nRows
行,例如
x[0,:]
for row in x:
# do something with the row
Common practice is to reshape x
(as needed) so it has at least 1 row.通常的做法是重塑
x
(根据需要),使其至少有 1 行。 In other words, change the shape from (n,)
to (1,n)
.换句话说,将形状从
(n,)
更改为(1,n)
。
x = np.atleast_2d(x)
does this nicely.这很好。 Inside a function, such a change to
x
won't affect x
outside it.在函数内部,对
x
这种更改不会影响其外部的x
。 This way you can treat x
as 2d through out your function, rather than constantly looking to see whether it is 1d v 2d.通过这种方式,您可以在整个函数中将
x
视为 2d,而不是不断查看它是否为 1d v 2d。
Python: How can I force 1-element NumPy arrays to be two-dimensional? Python:如何强制 1 元素 NumPy 数组为二维数组?
is one of many previous SO questions that asks about treating 1d arrays as 2d.是之前许多关于将一维数组视为二维数组的问题之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.