Numpy 3D数组索引:适用于2D,如何用于3D?

时间:2019-05-15 15:24:57

标签: python arrays numpy

我有3个numpy数组,如下所示。

import numpy as np
key_idx = np.array([1, 2, 1])  # both have same shape
out_idx = np.array([0, 3, 0])
max_out = out_idx.max()
output = np.zeros(shape=(len(key_idx), max_out + 1))

# output = 
# array([[0., 0., 0., 0.],
#        [0., 0., 0., 0.],
#        [0., 0., 0., 0.]])

我想增加由索引给出的值,如下所示:

key_idx = key_idx[np.newaxis, :] # convert to 2D
out_idx = out_idx[np.newaxis, :]
idx = (key_idx, out_idx)
np.add.at(output, idx, 1)

# output =
# array([[0., 0., 0., 0.],
#        [2., 0., 0., 0.],
#        [0., 0., 0., 1.]])

然后应用如下转换:

np.sum(np.amax(output, axis=1))
#3.0

但是现在我想对3D输出数组执行此操作,其中key_idx2D是2D数组,第一维表示table_id。请参考下图: enter image description here

我尝试过的

key_idx2D = np.array([[1, 2, 1], [2, 2, 2]])
output3D = np.zeros(shape=(key_idx2D.shape[0], len(key_idx), max_out + 1))
key_idx2D = key_idx[np.newaxis, :] # convert to 3D
out_idx = out_idx[np.newaxis, :]
idx3D = (key_idx2D, out_idx)
np.add.at(output3D, idx3D, 1)

#IndexError: index 2 is out of bounds for axis 0 with size 2

对于3D情况,我该怎么做?任何帮助表示赞赏。如图所示,它应该为每个table_id返回一个值数组。

注意:我可以使用循环来完成,但是会很慢。我需要更快的东西。

修改key_idx2D具有axis 0 = table_idaxis 1 = key_idout_idxaxis 0 = out_idkey_idx2Dout_idx都包含output ndarray唯一需要对其应用np.add.at()的索引。 我已经更新了该图以澄清这一点。

1 个答案:

答案 0 :(得分:0)

我正在发布答案,以防有人觉得有用。

key_idx2D = np.array([[1, 2, 1], [2, 2, 2]])
output3D = np.zeros(shape=(key_idx2D.shape[0], key_idx2D.shape[1], max_out + 1))
output3D.shape
#(2, 3, 4)

我需要做的是为第一个轴(即轴0)创建一个索引数组。

table_idx = np.array([0, 1]).reshape(-1, 1)
out_idx = np.array([0, 3, 0])
table_idx.shape, key_idx2D.shape, out_idx.shape
#((2, 1), (2, 3), (3,))

然后将所有索引数组以元组的形式发送到np.add.at

np.add.at(output3D, (table_idx, key_idx2D, out_idx), 1)
output3D

# array([[[0., 0., 0., 0.],
#         [2., 0., 0., 0.],
#         [0., 0., 0., 1.]],
#        [[0., 0., 0., 0.],
#         [0., 0., 0., 0.],
#         [2., 0., 0., 1.]]])

np.sum(np.amax(output3D, axis=2), axis=1)
#array([3., 2.])