简体   繁体   English

Numpy:使用索引数组设置 3D 数组中的值

[英]Numpy: Using an index array to set values in a 3D array

I have an indices array of shape (2, 2, 3) which looks like this:我有一个形状为 (2, 2, 3) 的indices数组,如下所示:

array([[[ 0,  6, 12],
        [ 0,  6, 12]],
       [[ 1,  7, 13],
        [ 1,  7, 13]]])

I want to use these as indices to set some values of a np.zeros matrix to 1. While the highest value in this example is a 13, I know that it can go up to 18. This is why I created one_hot = np.zeros((2, 2, 18)) array:我想使用这些作为索引np.zeros矩阵的某些值设置为 1。虽然此示例中的最大值是 13,但我知道它可以达到 go 到 18。这就是我创建one_hot = np.zeros((2, 2, 18))数组:

array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
       [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]])

Using the indices array, my desired outcome is this:使用indices数组,我想要的结果是这样的:

array([[[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]],
       [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]]])

I want to use numpy's advanced indexing sort of like this:我想像这样使用 numpy 的高级索引:

one_hot[indices] = 1

How can I do that?我怎样才能做到这一点?

A possible solution:一个可能的解决方案:

np.put_along_axis(one_hot, indices, 1, axis=2)

Output: Output:

[[[1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
  [1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]

 [[0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
  [0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM