Link_tester
Link_tester

Reputation: 1081

How to extract non-zero values of a numpy array

I have a numpy array and want to extract some values out of it. This is my array:

arr= array([[0, 0, 23, 28],
            [0, 19, 24, 29],
            [0, 20, 25, 30],
            [17, 21, 26, 31],
            [18, 22, 27, 32]])

I want to first sort the non-zero part of it and chage it into:

arr= array([[0, 0, 27, 32],
            [0, 22, 26, 31],
            [0, 21, 25, 30],
            [18, 20, 24, 29],
            [17, 19, 23, 28]])

Then, from the first column, I want to extract the last two rows (18 and 17). In the second column I have four none zero one: it means 2 more nonzero rows compred to previous column. So, I want two upper rows. In the third column I see five non-zero rows which is one row more than the second row, so I want the one row. In last column, the difference of its non-zero rows with the previous one zero, so I do not want any row from it. Finally. I want to have these extracted numbersas a list or numpy array:

result= [17, 18, 21, 22, 27]

I tried the following but it was successful at all:

result=[]
for m in range (len (arr[0,:])):
    for i in range (len (arr[:,m])):
        if arr[i,m]==0 and arr[i+1,m]!=0:
            b= arr[i+1:,m]
            result.append (b)

I appreciate any help in advance.

Upvotes: 2

Views: 1450

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

Let's try:

mask = arr != 0

# mask the 0 with infinity and sort
new_arr = np.sort(np.where(mask, arr, np.inf), axis=0)

# replace back:
arr[:] = np.where(mask, new_arr[::-1], 0)

# extract the result
result = arr[np.arange(arr.shape[0]),mask.argmax(axis=1)]

Upvotes: 4

Related Questions