假設有一個ndarray A = np.random.random([3, 5, 4]),并且我有另一個ndarray大小為 3 x 4 的索引,其條目是我想從第一個軸(維度為 5 的軸)中選擇的索引。如何使用 pythonic 代碼實作它?
例子:
A = [[[0.95220166 0.49801865 0.83217126 0.33361628]
[0.31751156 0.85899736 0.81965214 0.62465746]
[0.69251917 0.83201231 0.6089141 0.36589825]
[0.96674647 0.6056233 0.45515703 0.90552863]
[0.94524208 0.42422369 0.91633385 0.53177495]]
[[0.02883774 0.18012477 0.64642352 0.21295456]
[0.88475705 0.76020851 0.6888415 0.47958142]
[0.17306953 0.94981064 0.91468365 0.37297622]
[0.75924232 0.27537972 0.68803293 0.0904176 ]
[0.14596762 0.70103752 0.06090593 0.07920207]]
[[0.11092702 0.58002663 0.13553706 0.89662211]
[0.09146413 0.86212582 0.65908978 0.2995175 ]
[0.29025485 0.60788672 0.98595003 0.06762369]
[0.56136928 0.09623415 0.20178919 0.46531331]
[0.28628325 0.28215312 0.39670151 0.68243605]]]
Indices
= [[3 1 2 1]
[3 2 0 4]
[3 3 1 2]]
Result_I_want
= [[0.96674647, 0.85899736, 0.6089141, 0.62465746]
[0.75924232, 0.94981064, 0.64642352, 0.07920207]
[0.56136928, 0.09623415, 0.65908978, 0.06762369]]
uj5u.com熱心網友回復:
In [148]: A = np.arange(3*5*4).reshape([3, 5, 4])
In [151]: B = np.array([[3, 1, 2, 1],
...: [3, 2, 0, 4],
...: [3, 3, 1, 2]])
In [152]: B.shape
Out[152]: (3, 4)
In [153]: A.shape
Out[153]: (3, 5, 4)
應用于B中間維度,并使用形狀為 (3,1) 和 (4,) 的陣列作為其他兩個維度。他們broadcast一起選擇一個 (3,4) 元素陣列。
In [154]: A[np.arange(3)[:,None],B,np.arange(4)]
Out[154]:
array([[12, 5, 10, 7],
[32, 29, 22, 39],
[52, 53, 46, 51]])
uj5u.com熱心網友回復:
嘗試np.take_along_axis:
A = np.arange(3*5*4).reshape([3, 5, 4])
# B is the same as your sample data
np.take_along_axis(A, B[:,None,:], axis=1).reshape(B.shape)
輸出:
array([[12, 5, 10, 7],
[32, 29, 22, 39],
[52, 53, 46, 51]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/345552.html
標籤:Python 麻木的 片 numpy-ndarray
