簡體   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