This question is probably basic for some of you but it I am new to Python. I have an initial array:
initial_array = np.array ([1, 6, 3, 4])
I have another array.
value_array= np.array ([10, 2, 3, 15])
I want an array called output array which looks at the values in value_array and reorder the initial array.
My result should look like this:
output_array = np.array ([4, 1, 3, 6])
Does anyone know if this is possible to do in Python?
So far I have tried:
for i in range(4):
find position of element
CodePudding user response:
You can use numpy.argsort
to find sort_index from value_array
then rearrange the initial_array
base sort_index in the reversing order with [::-1]
.
>>> idx_sort = value_array.argsort()
>>> initial_array[idx_sort[::-1]]
array([4, 1, 3, 6])
CodePudding user response:
Yes, it is possible to do this in Python. You can use the numpy.argsort()
function to sort an array based on the values of another array. The following code example will give the desired output:
import numpy as np
initial_array = np.array([1, 6, 3, 4])
value_array= np.array([10, 2, 3, 15])
sort_indices = np.argsort(value_array)
output_array = initial_array[sort_indices]
print(output_array)
# Output: array([ 4, 1, 3, 6])
CodePudding user response:
You could use stack to put arrays together - basically adding column to initial array, then sort by that column.
import numpy as np
initial_array = np.array ([1, 6, 3, 4])
value_array = np.array ([10, 2, 3, 15])
output_array = np.stack((initial_array, value_array), axis=1)
output_array=output_array[output_array[:, 1].argsort()][::-1]
print (output_array)
[::-1] part is for descending order. Remove to get ascending. I am assuming initial_array and values_array will have same length.