简体   繁体   中英

Find most common value(exclude -1) in numpy 3d array where the corrsponding value in another array is 1

I have 2 arrays, array_a and array_b, both shape is (2,3,4).

What I want to do is to get the most common value at axis=2 in array_b where the corrsponding value in array_a is 1.

Here is my code. Is there any way to do this faster? Thanks.

array_a = np.array([[[-1,-1,-1,1], [-1,-1,-1,1], [-1,1,1,1]], [[-1,-1,1,1], [-1,1,1,1], [-1,1,1,1]]])
array_b = np.array([[[1,2,2,4], [0,0,1,3], [1,1,1,8]], [[0,1,0,3], [3,3,8,8], [3,3,0,1]]])
array_b[array_a!=1] = -1 
    # Only want to use the values in array_b where the corrsponding value in array_a is 1 

result = []
for row in np.ndindex(array_b.shape[:2]):
    count = Counter(array_b[row])
    del count[-1]
    result = np.append(result , count.most_common(1)[0][0])

If I haven't misunderstood the condition of axis = 2; removing the for-loop and using NumPy native selection would improve the performance, if the OP would use a larger dimension array.

select = array_b[array_a == 1] # pick all the values in array_b, 
                               # where the corresponding element in 
                               # array_a equals 1

val, cnt = np.unique(select, return_counts=True) # get the frequencies of 
                                                 # values

print( val[np.argmax(cnt)] )  # print the most frequent element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM