簡體   English   中英

在numpy數組中確保至少一定的維度

[英]ensuring at least a certain dimensionality in a numpy array

我的工具包中有以下功能,並且非常依賴它。 我發現很難相信沒有一個numpy內置來做這個,但我在numpy搜索可能的函數名稱,谷歌搜索這個問題的各種解釋,並沒有發現任何東西。 有東西嗎?

def project(a, maxdim):
    """
    Return a view of the numpy array <a> that has at least <maxdim>+1
    dimensions (pad a.shape with 1's on the right if necessary).
    """
    if isinstance(a, numpy.matrix) and maxdim > 1: a = numpy.asarray(a)
    else: a = a.view()
    a.shape += (1,) * (maxdim-len(a.shape)+1)
    return a

具有默認Fortran順序的MATLAB會自動在右側添加尺寸。 numpy是默認的C順序,並且更喜歡將它們附加在左側。

np.array采用ndmin參數,根據需要ndmin 1。

例如

In [89]: np.array([1,2,3],ndmin=4).shape
Out[89]: (1, 1, 1, 3)

有3個np.atleast_?d函數。

In [92]: np.atleast_2d([1,2,3]).shape
Out[92]: (1, 3)
In [93]: np.atleast_3d([1,2,3]).shape
Out[93]: (1, 3, 1)

atleast_3d用於np.dstack ,可能已經明確寫入該用途。

廣播時, numpy將根據需要預先設置尺寸; 等待他們的帖子需要你做出明確的行動。 這只是開發人員選擇的默認numpy

np.ones((3,4,5))+np.zeros((5))

np.array有一個copy參數

In [113]: x=np.array([1,2,3])
In [114]: y=np.array(x, ndmin=3,copy=False)

In [117]: y.__array_interface__['data']
Out[117]: (152332976, False)
In [118]: x.__array_interface__['data']
Out[118]: (152332976, False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM