0

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
komodovaran_
  • 1,940
  • 16
  • 44

2 Answers2

1
>>> 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])
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

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

Rahul
  • 161
  • 2
  • 6
  • Thanks for making it clear where my fault lies. You may want to edit the ambiguity in the final line, as that's what I *get* but not what I *hope to get*. – komodovaran_ Jun 11 '19 at 09:49