简体   繁体   English

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

[英]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 3rows 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.

相关问题 Python Numpy.ndarray.shape限制 - Python Numpy.ndarray.shape limit 为什么 pylint 为 numpy.ndarray.shape 返回“unsubscriptable-object”? - Why pylint returns `unsubscriptable-object` for numpy.ndarray.shape? 如何制作“ ndarrays的ndarray的元组”? - How can I make a “tuple of an ndarray of ndarrays”? IndexError:访问numpy ndarray形状时元组索引超出范围 - IndexError: tuple index out of range while accessing numpy ndarray shape 如何获取两个不同的numpy.ndarray子类的__matmul__以返回特定的子类? - How do I get __matmul__ of two different numpy.ndarray subclasses to return a particular subclass? Numpy: 如何 map f: (shape (3) ndarray) --> (float) over an ndarray of shape (...,3) 以获得 ndarray of shape (...)? - Numpy: How to map f: (shape (3) ndarray) --> (float) over an ndarray of shape (…,3) to get ndarray of shape (…)? 我有一个变量作为元组,如何将其作为字符串返回 - I have a variable as a tuple how can I return it as a string 如何删除 Pandas 系列 (pandas.core.series.Series) 的索引以返回 numpy.ndarray? - How can I drop the index of a Pandas Series (pandas.core.series.Series) to return a numpy.ndarray? 如何将两种不同类型的数据(字符串和整数)添加到numpy ndarray中 - How can I add two different type of data, string and int, into numpy ndarray numpy dtype ValueError:固定类型元组中的无效形状 - 我该如何解决? - numpy dtype ValueError: invalid shape in fixed-type tuple - how can I get around it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM