我有一個這樣的索引陣列:
idx = np.array([3,4,1], [0,0,0], [1,4,1], [2,0,2]]
A和一個形狀為零的陣列4x5
我想讓 in 的所有索引idx為A1
對于上面的例子,最終的陣列應該是:
[[0,1,0,1,1], # values at index 3,4,1 are 1
[1,0,0,0,0], # value at index 0 is 1
[0,1,0,0,1], # values at index 1,4 are 1
[1,0,1,0,0]] # values at index 0,2 are 1
如何在 numpy 中做到這一點?
uj5u.com熱心網友回復:
使用花哨的索引:
A = np.zeros((4, 5), dtype=int)
A[np.arange(len(idx))[:,None], idx] = 1
或者numpy.put_along_axis:
A = np.zeros((4, 5), dtype=int)
np.put_along_axis(A, idx, 1, axis=1)
更新A:
array([[0, 1, 0, 1, 1],
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 1, 0, 0]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/528665.html
下一篇:如何從Pandas的嵌套串列列中獲取最小值?為什么numpy.min()在numpy.mean()有效的情況下不起作用?
