Home > Net >  Swap/order values by row
Swap/order values by row

Time:10-30

I have (N,2) numpy array :

 [3,5]
 [4,2]
 [1,6]
 [5,4]
 .....

I want to swap the values on every row so that the bigger value is FIRST

 [5,3]
 [4,2]
 [6,1]
 [5,4]
 .....

CodePudding user response:

You could use something like this:

array.sort()
array = array[:, ::-1]

if array is your numpy array

CodePudding user response:

ori_arr = np.array([[3, 5], [4, 2], [1, 6], [5, 4]])
print('''{}
The original array:
{}
'''.format("="*20, ori_arr))
# Straight forward way
for i in range(len(ori_arr)):
    ori_arr[i] = sorted(ori_arr[i], reverse=True)
print('''{}
The swapped array:
{}
'''.format("="*20, ori_arr))

The results are: enter image description here

CodePudding user response:

Below is the answer i tried and i got the output , there could be efficient methods as well.

import numpy as np
    
    x=np.array([[1,2],[3,4],[7,6]])
    
    for i  in x :
        if i[0] >= i[1]:
        else:
            a= i[0]
            i[0]= i[1]
            i[1]= a
    
    print(x)
  • Related