簡體   English   中英

如何根據條件更改 2d numpy 數組的元素

[英]How to change 2d numpy array's element based on condition

假設我有三個 2D numpy 數組和一個加權 1D numpy 數組,我想將其加權到數組中的某個特定元素

import numpy as np
A= np.array([[2,0,2,2],[0,0,1,1],[1,2,1,0]])
B = np.array([[2,1,1,0],[2,2,0,2],[0,0,0,2]])
C = np.array([[0,0,3,2],[1,2,2,1],[2,3,1,5]])
    
Weight = np.array([0. , 0.5, 2. ])
Weight.reshape(-1,1)

第一個條件:當我們對這些數組求​​和時,如下所示

sum = np.sum(A,axis=0) +np.sum(B,axis=0) + np.sum(C,axis=0) 

對於大於10 的任何內容,我們選擇如下所示的數組。

#selecting last 2 columns
A_1 = A[:,np.sum(A,axis=0) +np.sum(B,axis=0) + np.sum(C,axis=0)  > 10]
B_1 = B[:,np.sum(A,axis=0) +np.sum(B,axis=0) + np.sum(C,axis=0)  > 10]
C_1 = C[:,np.sum(A,axis=0) +np.sum(B,axis=0) + np.sum(C,axis=0)  > 10]

(array([[2, 2],
        [1, 1],
        [1, 0]]),
 array([[1, 0],
        [0, 2],
        [0, 2]]),
 array([[3, 2],
        [2, 1],
        [1, 5]]))

第二個條件:當A_1 + B_1 - C_1 <0時,我們想修改元素為(A+B)*weight

diff =  A_1 + B_1 - C_1 <0

(array([[False, False],
        [ True, False],
        [False,  True]]),
 array([[ 0,  0],
        [-1,  2],
        [ 0, -3]]))

對於我們有 True 的地方,我們想將 C_1 更改為

[[3, 2],
[(1+0)*0.5, 1],
[1, (0+2)*2.0]]

(1+0)*0.5 因為 0.5 在第二行, (0+2)*2.0 因為 2.0 在第三行

因此最后 C 變成..

array([[0, 0, 3, 2],
        [1, 2, (1+0)*0.5, 1],
        [2, 3, 1, (0+2)*2.0]]))

我想在不使用循環的情況下實現這個結果C .. 任何幫助將不勝感激。

您可以使用掩碼:

AB = A+B
m1 = (AB+C).sum(0)>10
m2 = (AB-C) < 0

m = m1&m2

C = C.astype(float)
C[m] = (AB*Weight)[m]

更新C

array([[0. , 0. , 3. , 2. ],
       [1. , 2. , 0.5, 1. ],
       [2. , 3. , 1. , 4. ]])

暫無
暫無

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

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