1

I have the following ndarray :

c_dist = [[0.         5.83095189]
 [2.23606798 3.60555128]
 [5.83095189 0.        ]
 [5.83095189 2.82842712]
 [4.12310563 2.23606798]]

and I would like for each sub-array to replace the min with 1 and the max with 0, in order to obtain the following :

[[1. 0.]
 [1. 0.]
 [0. 1.]
 [0. 1.]
 [0. 1.]]

I used the following :

for i in range(len(c_dist)):
    max_of_row = c_dist[i].max()
    for elements_of_row in range(len(c_dist[i])):
        if c_dist[i][elements_of_row] == max_of_row:
            c_dist[i][elements_of_row] = 1
        else:
            c_dist[i][elements_of_row] = 0

but it is obviously not very elegant. Is there an python way of doing the comparison array by array please ?

1
  • is the cdist.shape = (n, 2) always True? Commented Nov 18, 2020 at 11:32

2 Answers 2

3

Try this in one line:

c_dist = [[0. ,5.83095189], 
          [2.23606798 ,3.60555128], 
          [5.83095189 ,0.        ], 
          [5.83095189 ,2.82842712], 
          [4.12310563 ,2.23606798]]  

new_list = [[int(i<=j), int(i>j)] for i,j in c_dist]

The result will be:

In [6]: new_list                                                                                                                                                                                                                                                                          
Out[6]: [[1, 0], [1, 0], [0, 1], [0, 1], [0, 1]]
Sign up to request clarification or add additional context in comments.

3 Comments

Your welcome. please check the gray button and turn it to green if it was helpful.
Hi @Mehrdad, actually my example should state that there are cases when i an have more than 2 column. ei: the number of column is not fixed.
@FrankyDoul In those cases... what the logic. can you add an example of what you are saing.
1

If you have more than 2 columns:

out = c_dist.copy()
np.put_along_axis(out, c_dist.argmax(0), 1)
np.put_along_axis(out, c_dist.argmin(0), 0)

Or if there are multiple max and min values per row:

out = np.where(c_dist == c_dist.max(0, keepdims = True), 1, c_dist)
out = np.where(c_dist == c_dist.min(0, keepdims = True), 0, out)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.