zip
获取沿每个轴的索引
IIUC,你已经完成了大部分工作。
idx
>>> [*zip(*idx)]
[(0, 0, 0, 0, 0, 1, 1, 1, 1),
(0, 0, 1, 2, 2, 0, 0, 0, 1),
(0, 1, 0, 1, 2, 0, 1, 2, 2)]
>>> t, y, x = zip(*idx)
>>> DATA[t, :, y, x]
array([[26, 37],
[58, 34],
[69, 67],
[50, 80],
[76, 3],
[ 2, 46],
[19, 28],
[12, 81],
[81, 96]])
>>> DATA[t, :, y, x].mean(0)
array([43.66666667, 52.44444444])
使用
np.where
一种更简单的方法来获得
numpy.where
:
>>> np.where(COND)
(array([0, 0, 0, 0, 0, 1, 1, 1, 1], dtype=int64),
array([0, 0, 1, 2, 2, 0, 0, 0, 1], dtype=int64),
array([0, 1, 0, 1, 2, 0, 1, 2, 2], dtype=int64))
numpy.nonzero
>>> np.nonzero(COND)
(array([0, 0, 0, 0, 0, 1, 1, 1, 1], dtype=int64),
array([0, 0, 1, 2, 2, 0, 0, 0, 1], dtype=int64),
array([0, 1, 0, 1, 2, 0, 1, 2, 2], dtype=int64))
直接使用条件数组
ndarray
s是
numpy.transpose
,正如您在链接文章中所看到的,在您的问题中,索引时,维度是左对齐的,但当前形式的数组不适合这种索引,因此,如果聚合维度位于最右侧,而索引维度位于左侧,那么就可以了。
因此,如果您的数据可以重新排序:
Instead of:
dim = (2, 2, 3, 3)
axis-> 0, 1, 2, 3
It were:
dim = (2, 3, 3, 2)
axis-> 0, 2, 3, 1
这会奏效的。
使用重新排列轴
np.transpose
你可以用
numpy.transpose
为此:
>>> np.transpose(DATA, axes=(0,2,3,1))[COND==1].mean(axis=0)
array([43.66666667, 52.44444444])
np.roll
roll
您的轴(=1)到末端(即第四维),使用
numpy.rollaxis
>>> np.rollaxis(DATA, 1, 4)[COND==1].mean(0)
array([43.66666667, 52.44444444])
使用移动轴
np.转置
或者,你可以
move
你的轴心来自
source
维度到
destination
np.moveaxis
>>> np.moveaxis(DATA, source=1, destination=3)[COND==1].mean(0)
array([43.66666667, 52.44444444])