![](/img/trans.png)
[英]How to get a 2D NumPy array with value 1 at indices represented by values in 1D NumPy array (Python)
[英]Python: Replace 2D numpy array filled with indices by values from a 1D array
我有anxm numpy python 陣列。 該數組的值介於 0 和 10 之間,與一維 numpy 數組的索引一致(一維數組的長度 = 11,因此為 0-10)。 此一維數組存儲任意值。 我現在想用一維數組中的相應值替換我的二維數組的索引值。
我怎樣才能做到這一點?
干杯諾克森
numpy 很簡單: result = values_1d[arr_idxs_2d]
看:
>>> import numpy as np
>>> imin, imax = 0, 9
>>> values_1d = np.random.randn(imax+1)
>>> values_1d
array([-0.80355548, 1.00645905, -1.17436992, -1.52008027, 0.73544379,
-0.72175806, -0.69933584, -0.50195895, -0.04588092, 0.86542796])
>>> arr_idxs_2d = np.random.randint(imin, imax, (4, 5))
>>> arr_idxs_2d
array([[6, 7, 4, 3, 1],
[8, 8, 3, 7, 7],
[1, 1, 5, 3, 2],
[6, 2, 3, 6, 8]])
>>> values_1d[arr_idxs_2d]
array([[-0.69933584, -0.50195895, 0.73544379, -1.52008027, 1.00645905],
[-0.04588092, -0.04588092, -1.52008027, -0.50195895, -0.50195895],
[ 1.00645905, 1.00645905, -0.72175806, -1.52008027, -1.17436992],
[-0.69933584, -1.17436992, -1.52008027, -0.69933584, -0.04588092]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.