Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two values in a numpy array.

Is there something more efficient than the following code to swap two values of a numpy 1D array?

input_seq = arange(64)

ix1 = randint(len(input_seq))
ixs2 = randint(len(input_seq))

temp = input_seq[ix2]
input_seq[ix2] = input_seq[ix1] 
input_seq[ix1] = temp
like image 299
Gioelelm Avatar asked Apr 03 '14 19:04

Gioelelm


2 Answers

You can use tuple unpacking. Tuple unpacking allows you to avoid the use of a temporary variable in your code (in actual fact I believe the Python code itself uses a temp variable behind the scenes but it's at a much lower level and so is much faster).

input_seq[ix1], input_seq[ix2] = input_seq[ix2], input_seq[ix1]

I have flagged this question as a duplicate, the answer in the dupe post has a lot more detail.

like image 61
Ffisegydd Avatar answered Nov 07 '22 15:11

Ffisegydd


I see you're using numpy arrays. In that case, you can also do this:

input_seq[[ix1, ix2]] = input_seq[[ix2, ix1]]
like image 43
Lewistrick Avatar answered Nov 07 '22 17:11

Lewistrick