Home > Software engineering >  Rearrange specific array elements in ascending and descending orders in Python
Rearrange specific array elements in ascending and descending orders in Python

Time:08-03

I have an array A. I want to rearrange elements at specific positions in A according to list B in ascending and descending order. I present the expected outputs.

import numpy as np

A= np.array([[18691.58878504673 , 19625.331510678385, 19147.082987707967,
        20657.27032098752 , 21505.366397879847, 19383.257708228517,
        20128.083079101947, 20932.43758022147 , 20389.243615449053,
        21215.03459489576 , 19873.528207732994, 18506.523549551217]])

B=[3,5,6,8]

for i in range(0,len(B)):
    A[:,B[i]]

The expected output is

Ascending order:

array([[18691.58878504673 , 19625.331510678385, 19147.082987707967,
        19383.257708228517 , 21505.366397879847, 20128.083079101947,
        20389.243615449053, 20932.43758022147 , 20657.27032098752,
        21215.03459489576 , 19873.528207732994, 18506.523549551217]])

Descending order:

array([[18691.58878504673 , 19625.331510678385, 19147.082987707967,
         20657.27032098752, 21505.366397879847, 20389.243615449053,
        20128.083079101947, 20932.43758022147 , 19383.257708228517,
        21215.03459489576 , 19873.528207732994, 18506.523549551217]])

CodePudding user response:

Following should do it (though someone else might be able to find a quicker way):

import numpy as np

A = np.array([[18691.58878504673 , 19625.331510678385, 19147.082987707967,
        20657.27032098752 , 21505.366397879847, 19383.257708228517,
        20128.083079101947, 20932.43758022147 , 20389.243615449053,
        21215.03459489576 , 19873.528207732994, 18506.523549551217]])

B = [3,5,6,8]
    
asc = np.sort(A[:,B])
desc = asc[:,::-1]

A_asc = np.copy(A)
A_asc[:,B]=asc
A_desc = np.copy(A)
A_desc[:,B]=desc

expected_asc = np.array([[18691.58878504673 , 19625.331510678385, 19147.082987707967,
        19383.257708228517 , 21505.366397879847, 20128.083079101947,
        20389.243615449053, 20932.43758022147 , 20657.27032098752,
        21215.03459489576 , 19873.528207732994, 18506.523549551217]])

expected_desc = np.array([[18691.58878504673 , 19625.331510678385, 19147.082987707967,
         20657.27032098752, 21505.366397879847, 20389.243615449053,
        20128.083079101947, 20932.43758022147 , 19383.257708228517,
        21215.03459489576 , 19873.528207732994, 18506.523549551217]])

print(np.array_equal(A_asc,expected_asc))
# True
print(np.array_equal(A_desc,expected_desc))
# True

I'm using copies here. But you could of course simply do A[:,B]=asc and A[:,B]=desc if you want to update A.

  • Related