簡體   English   中英

根據該數組中的值將值插入到numpy數組中

[英]Inserting values into a numpy array based on values in that array

如果我有一個數組:

a = np.array([[1,2,3]])

我可以根據數組中的值向該數組添加一個值。

a = np.insert(a,3,(0.299+a[0][1]*0.587+a[0][2]*0.114))

這將給我以下數組。

array([1, 2, 3, 1.815])

到現在為止還挺好。 但是現在我想對具有以下形狀的數組執行此操作。

a = np.array(
    [
        [[1,2,3],[3,4,5]],
        [[6,7,8],[9,10,11]]
    ])

array([[[ 1,  2,  3],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

有沒有不用for循環就可以做到這一點的方法?

編輯原始問題有一個“最小工作示例”,由於過於簡化,導致使用了np.sum()函數。 現在它遵循下面的公式,我需要(0.299 * R + 0.587 * G + 0.114 * B)

您沒有指定所需的輸出,但是我想這就是您想要的:

a = np.insert(a, 3, a.sum(axis=-1), axis=-1)
a
#[[[ 1  2  3  6]
#  [ 3  4  5 12]]
#
# [[ 6  7  8 21]
#  [ 9 10 11 30]]]

如果沒有for循環,那么您將不得不遍歷所有項目,因此恐怕您無法避免。 或至少復制行為。

以下內容有望使您更接近實際應用:

#Define a function to apply to the matrix
def f(x, ar):
    return np.append(next(ar),x[0]*0.299+x[1]*0.587+x[2]*0.114)

#Create an iterator for semi-efficient stepping through the matrix elements
b = iter(a.reshape((a.shape[0]*a.shape[1],-1)))

#create output array; syntax:
#np.apply_along_axis(1D-function,axis_to_apply_along,object_to_apply_to,optional_arguments)
vals = np.apply_along_axis(f,2,a,b)

#vals
#Out[440]: 
#array([[[  1.   ,   2.   ,   3.   ,   1.815],
#        [  3.   ,   4.   ,   5.   ,   3.815]],
#
#       [[  6.   ,   7.   ,   8.   ,   6.815],
#        [  9.   ,  10.   ,  11.   ,   9.815]]])

但是,for循環在循環結束序列上調用iter() ,並在結果上使用next()調用。 因此,以上功能基本上以替代方式實現了for循環。 現在,我們唯一希望有所改變的是,我們避免了遍歷錯誤的事物,因此最終節省了一些時間。

您可以嘗試:

a = np.array([[[1,2,3],[3,4,5]],[[6,7,8],[9,10,11]]]).astype(np.float_)
a = np.concatenate((a, 0.299*a[:,:,0:1] + 0.587 * a[:,:,1:2] + 0.114*a[:,:,2:3]), axis = 2 )

這給了我:

array([[[  1.   ,   2.   ,   3.   ,   1.815],
        [  3.   ,   4.   ,   5.   ,   3.815]],
       [[  6.   ,   7.   ,   8.   ,   6.815],
        [  9.   ,  10.   ,  11.   ,   9.815]]])

注意:如果需要單精度,請使用np.float32而不是np.float_ ,它實際上對應於雙精度( 此處為numpy類型的參考 )。 當然,如果a已經具有正確的類型,則無需進行轉換。

暫無
暫無

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

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