下面是一个示例代码,按照与其索引相关的值对numpy的3D数组元素进行分组:
import numpy as np
# 创建一个3D数组
arr = np.array([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]],
[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]])
# 获取数组的形状
shape = arr.shape
# 创建一个与原数组形状相同的索引数组
indices = np.indices(shape)
# 按照索引数组的值对原数组进行分组
grouped = np.zeros(shape, dtype=np.object)
for i in range(shape[0]):
for j in range(shape[1]):
for k in range(shape[2]):
index_value = indices[:, i, j, k]
grouped[index_value[0], index_value[1], index_value[2]] = arr[i, j, k]
# 打印分组后的数组
print(grouped)
输出结果为:
[[[1 2 3]
[4 5 6]
[7 8 9]]
[[10 11 12]
[13 14 15]
[16 17 18]]
[[19 20 21]
[22 23 24]
[25 26 27]]]
在这个示例中,我们使用np.indices()
函数创建了一个与原数组形状相同的索引数组indices
。然后,我们使用for
循环遍历原数组的每个元素,并将其根据索引值放入一个新的3D数组grouped
中。最后,我们打印出了分组后的数组。