Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rearrange array based upon index array

I'm looking for a one line solution that would help me do the following.

Suppose I have

array = np.array([10, 20, 30, 40, 50]) 

I'd like to rearrange it based upon an input ordering. If there were a numpy function called arrange, it would do the following:

newarray = np.arrange(array, [1, 0, 3, 4, 2]) print newarray      [20, 10, 40, 50, 30] 

Formally, if the array to be reordered is m x n, and the "index" array is 1 x n, the ordering would be determined by the array called "index".

Does numpy have a function like this?

like image 411
hlin117 Avatar asked Oct 04 '14 15:10

hlin117


People also ask

How do you rearrange indexes in an array?

Step 1: Create a function that takes the two input arrays array[] and index[] and reorders based on index array. Step 2: In the function, a) Create an auxiliary array temp same size of given arrays. c) Copy this temp array as a given array and change index array based on indexes.

How do you rearrange arrays in C++?

Approach used in the below program is as followsDeclare a variable as max_val and set it with arr[size - 1] + 1. Start loop FOR from i to 0 till i less than size. Inside the loop, check IF i % 2 = 0 then set arr[i] to arr[i] + (arr[max] % max_val) * max_val and decrement the max by 1.

How do you rearrange the order of an array in Java?

Use the sort() method of the Arrays class to rearrange an array.


2 Answers

You can simply use your "index" list directly, as, well, an index array:

>>> arr = np.array([10, 20, 30, 40, 50]) >>> idx = [1, 0, 3, 4, 2] >>> arr[idx] array([20, 10, 40, 50, 30]) 

It tends to be much faster if idx is already an ndarray and not a list, even though it'll work either way:

>>> %timeit arr[idx] 100000 loops, best of 3: 2.11 µs per loop >>> ai = np.array(idx) >>> %timeit arr[ai] 1000000 loops, best of 3: 296 ns per loop 
like image 99
DSM Avatar answered Oct 18 '22 04:10

DSM


for those whose index is 2d array, you can use map function. Here is an example:

a = np.random.randn(3, 3) print(a) print(np.argsort(a))  print(np.array(list(map(lambda x, y: y[x], np.argsort(a), a)))) 

the output is

[[-1.42167035  0.62520498  2.02054623]  [-0.17966393 -0.01561566  0.24480554]  [ 1.10568543  0.00298402 -0.71397599]] [[0 1 2]  [0 1 2]  [2 1 0]] [[-1.42167035  0.62520498  2.02054623]  [-0.17966393 -0.01561566  0.24480554]  [-0.71397599  0.00298402  1.10568543]] 
like image 41
Jiaming Huang Avatar answered Oct 18 '22 03:10

Jiaming Huang