komodovaran_
komodovaran_

Reputation: 2012

Swapping two integers in numpy array leads to IndexError

I first tried Swap two values in a numpy array.

But this seemingly simple problem leads to index errors or incorrect results, so I must be doing something wrong... but what?

import numpy as np

# Swap 1 and 3, leave the 0s alone!
i = np.array([1, 0, 1, 0, 0, 3, 0, 3])

# Swaps incorrectly
i[i==1], i[i==3] = 3, 1

# IndexError
i[i==1, i==3] = i[i==3, i==1]

# IndexError
i[[i==1, i==3]] = i[[i==3, i==1]]

# IndexError
ix1 = np.argwhere(i==1)
ix3 = np.argwhere(i==3)
i[[ix1, ix3]] = i[[ix3, ix1]]

# Swaps incorrectly
i[np.argwhere(i==1)], i[np.argwhere(i==3)] = 3, 1

Upvotes: 0

Views: 88

Answers (2)

Rahul
Rahul

Reputation: 181

You used tuple swap to swap your values. It is not the safest way for numpy arrays. The answer for your question has already been posted.

https://stackoverflow.com/a/14933939/11459926

Upvotes: 0

ForceBru
ForceBru

Reputation: 44888

>>> import numpy as np
>>> i = np.array([1, 0, 1, 0, 0, 3, 0, 3])
>>> i
array([1, 0, 1, 0, 0, 3, 0, 3])
>>> a, b = i ==3, i == 1  # save the indices
>>> i[a], i[b] = 1, 3
>>> i
array([3, 0, 3, 0, 0, 1, 0, 1])

Upvotes: 1

Related Questions