【发布时间】:2019-06-11 09:11:18
【问题描述】:
我第一次尝试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
【问题讨论】:
-
尝试 np.where 定位给定值的索引:i[np.where(i==1)] = some_value