我第一次尝试Swap two values in a numpy array.
但是这个看似简单的问题会导致索引错误或错误的结果,所以我必须做错了什么……但是什么呢?
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
答案 0 :(得分: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])
答案 1 :(得分:0)
您使用元组交换来交换值。对于numpy数组来说,这不是最安全的方法。 您的问题的答案已经发布。