I have arr0 array for sorting value in ascending order according to rand
arr0 = np.array([ 0, 0, 0, 0, 500, 0, 0, 0, 0, 0, 1500,
0, 0, 0, 0, 0, 500, 0])
The random values for each column are:
rand=np.array([0.56451814, 0.36241843, 0.91447101, 0.58075664, 0.33733125,
0.81299872, 0.33180448, 0.15316298, 0.72839908, 0.41570189,
0.22387386, 0.6321233 , 0.97283938, 0.21228428, 0.7380092 ,
0.70700763, 0.10289023, 0.79383754])
Then I ascend an order arr0 following array rand
x = np.array(arr0)
y = np.array(rand)
sort = np.argsort(y)
numpy_array = np.array(x[sort])
zz = numpy_array.reshape(1,18)
print(zz)
Out:
array([[ 500, 0, 0, 1500, 0, 500, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0]])
My target, I would like to count the source each column in arr0 after ascending order,for example, the first 500 has the random smallest value and it coms from column number 17 in arr0 array.
Out:
array([[ '17' 500, '8' 0, '14' 0, '11' 1500, '7' 0, '5' 500, '2' 0, ..., '13' 0]])
What would you recommend? Thank you
>Solution :
Try using np.argsort:
import numpy as np
arr0 = np.array([0, 0, 0, 0, 500, 0, 0, 0, 0, 0, 1500, 0, 0, 0, 0, 0, 500, 0])
rand = np.array([0.56451814, 0.36241843, 0.91447101, 0.58075664, 0.33733125,
0.81299872, 0.33180448, 0.15316298, 0.72839908, 0.41570189,
0.22387386, 0.6321233 , 0.97283938, 0.21228428, 0.7380092,
0.70700763, 0.10289023, 0.79383754])
# Get the indices that would sort the rand array
sort_indices = np.argsort(rand)
# Use the sorted indices to sort arr0 and get the original indices
sorted_arr0 = arr0[sort_indices]
original_indices = sort_indices
# Reshape the sorted arr0 and original indices
sorted_arr0 = sorted_arr0.reshape(1, 18)
original_indices = original_indices.reshape(1, 18)
# Combine the original indices and sorted arr0
result = np.empty((2, sorted_arr0.shape[1]), dtype=sorted_arr0.dtype)
result[0] = original_indices
result[1] = sorted_arr0
print(result.T) # Transpose the result to get the desired format
Output:
[[ 16 500]
[ 7 0]
[ 13 0]
[ 10 1500]
[ 6 0]
[ 4 500]
[ 1 0]
[ 9 0]
[ 0 0]
[ 3 0]
[ 11 0]
[ 15 0]
[ 8 0]
[ 14 0]
[ 17 0]
[ 5 0]
[ 2 0]
[ 12 0]]
Note: python/numpy uses 0-based indexing. If you desire, I will leave it as an exercise for you to convert it into 1-based indexing.