我有一個列表值的numpy
陣列,如:NumPy的陣列,改變不在指數
a = np.arange(30)
我知道我可以代替例如使用花哨的索引位於位置indices=[2,3,4]
值:
a[indices] = 999
但是,如何替換不在indices
位置的值?會是下面的東西?
a[ not in indices ] = 888
謝謝!
我有一個列表值的numpy
陣列,如:NumPy的陣列,改變不在指數
a = np.arange(30)
我知道我可以代替例如使用花哨的索引位於位置indices=[2,3,4]
值:
a[indices] = 999
但是,如何替換不在indices
位置的值?會是下面的東西?
a[ not in indices ] = 888
謝謝!
我不知道一個乾淨的方式做這樣的事情:
mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool)
mask[indices] = False
a[~mask] = 999
a[mask] = 888
當然,如果你喜歡使用numpy的數據類型,你可以使用dtype=np.bool_
- 輸出不會有任何差異。這只是一個偏好問題。
很顯然,沒有通用的not
運算符集。你的選擇是:
a
形狀)減去你的indices
集,但是這將是一個有點難以實施和閱讀。for
-loop是你最好的選擇,因爲你一定要使用你的索引排序的事實)。創建一個充滿新值的新數組,並有選擇地從舊數組中複製索引。
b = np.repeat(888, a.shape)
b[indices] = a[indices]
僅適用於以一維數組:
a = np.arange(30)
indices = [2, 3, 4]
ia = np.indices(a.shape)
not_indices = np.setxor1d(ia, indices)
a[not_indices] = 888
就克服類似的情況,解決了這個辦法:
a = np.arange(30)
indices=[2,3,4]
a[indices] = 999
not_in_indices = [x for x in range(len(a)) if x not in indices]
a[not_in_indices] = 888
爲什麼不使用'np.ones_like' – jamylak
@jamylak - 因爲我需要看關於'np.ones_like'的文檔,但我知道'np.ones'是如何工作的;-) – mgilson
在附註上,你可以用'numpy.where'來調用最後幾行代碼(這是它真的有用的主要案例)。例如。 'a = np.where(mask,888,999)'。 –