【发布时间】:2017-08-03 16:38:05
【问题描述】:
我有一个尺寸为 [t, z, x, y] 的 numpy 数组“数据”。这 维度代表时间 (t) 和三个空间维度 (x, y, z)。 我有一个单独的索引数组“idx”,维度为 [t, x, y] 描述数据中的垂直坐标:idx 中的每个值描述一个 数据中的单个垂直级别。
我想从 idx 索引的数据中提取值。我已经做到了 成功使用循环(下)。我已经阅读了几篇SO threads 和numpy's indexing docs,但我无法让它更加pythonic/vectorized。
有没有一种简单的方法让我不太对劲?或者可能是循环 无论如何都是一种更清晰的方法......
import numpy as np
dim = (4, 4, 4, 4) # dimensions time, Z, X, Y
data = np.random.randint(0, 10, dim)
idx = np.random.randint(0, 3, dim[0:3])
# extract vertical indices in idx from data using loops
foo = np.zeros(dim[0:3])
for this_t in range(dim[0]):
for this_x in range(dim[2]):
for this_y in range(dim[3]):
foo[this_t, this_x, this_y] = data[this_t,
idx[this_t, this_x, this_y],
this_x,
this_y]
# surely there's a better way to do this with fancy indexing
# data[idx] gives me an array with dimensions (4, 4, 4, 4, 4, 4)
# data[idx[:, np.newaxis, ...]] is a little closer
# data[tuple(idx[:, np.newaxis, ...])] doesn't quite get it either
# I tried lots of variations on those ideas but no luck yet
【问题讨论】:
-
data.swapaxes(0, 1)[idx]? -
stackoverflow.com/a/44868461/901925 使用 3d 数组进行这种分配。这个想法应该适用于您的 4d 案例。我们的想法是获取 3 个数组(来自
ogrid),让您可以执行data[I, idx, J, K]