Python 交换numpy数组中的两个整数会导致索引错误
我第一次试过 但这个看似简单的问题会导致索引错误或不正确的结果,所以我一定是做错了什么。。。但是什么呢Python 交换numpy数组中的两个整数会导致索引错误,python,numpy,Python,Numpy,我第一次试过 但这个看似简单的问题会导致索引错误或不正确的结果,所以我一定是做错了什么。。。但是什么呢 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
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
您使用元组交换来交换值。对于numpy阵列来说,这不是最安全的方法。 您的问题的答案已发布
试试np.where来定位给定值的索引:i[np.where(i==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])