[英]Python: Replace 2D numpy array filled with indices by values from a 1D array
[英]How to get a 2D NumPy array with value 1 at indices represented by values in 1D NumPy array (Python)
如何在 Python 中的 1D np.array 中的值表示的索引處獲取值為 1 的 2D np.array。
例子:
[1, 2, 5, 1, 2]
應轉換為
[[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]]
在這里,您已經預先知道新數組的寬度 (shape[2]) 值。
我可以手動完成,但是有什么方法可以直接使用 NumPy 方法來加快執行速度嗎? 我的數組的維度非常大,我必須在所有迭代中都這樣做。 因此,為每次迭代手動執行此操作在計算上要求很高。
您可以使用np.zeros
創建一個包含零的數組。 數組的形狀應該是(len(1D array), max(1D array)+1)
。 然后使用 NumPy 的索引。
idx = [1, 2, 5, 1, 2]
shape = (len(idx), max(idx)+1)
out = np.zeros(shape)
out[np.arange(len(idx)), idx] = 1
print(out)
[[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 1.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.