我有一个4D矩阵,A(形状为[251,6,60141]),它包含很多NaN。我想把这个矩阵重塑成另一个矩阵B(形状为[73,6,60141])。换言之,在axis=0中,我要取不规则间隔步的numpy.nanmean()。有没有办法有效地做到这一点?
我希望下面代码中的循环说明了我的愿望,但我认为它不起作用,因为它以(似乎)无休止的运行时警告循环结束:
“/opt/anaconda3/lib/python3.4/site packages/numpy/lib/nanfunctions.py:598:运行时警告:空切片的平均值
warning.warn(“空切片的平均值”,runtimewarning)
import numpy as np
A = np.full(([251,6,60,141]), np.nan) # Create matrix A full of NaNs
# Assign some random values in random grid boxes in A
A[0, 1, 2, 3] = 4
A[1, 2, 3, 4] = 5
A[2, 3, 4, 5] = 6
A[3, 4, 5, 6] = 7
# Create the 1D array of the number of rows I want to average together in each interval
intvl = [0, 5, 2, 2, 1, 6, 5, 4, 1, 6, 2, 2, 3, 2, 2, 5, 6, 3, 3, 3, 3, 3, 3, 3, 2, 6, 3, 6, 3, 1, 6, 3, 6, 1, 4, 6, 3, 3, 2, 2, 3, 4, 2, 5, 1, 3, 1, 3, 1, 6, 4, 2, 3, 5, 5, 5, 7, 4, 2, 3, 4, 3, 2, 3, 5, 3, 2, 7, 5, 3, 5, 3, 3, 2]
# Sum the intvl array stepwise
intvl_cs = np.cumsum(intvl)
# Loop to perform the interval summation
B = np.full(([len(intvl),6,60,141]), np.nan) # Create the matrix B, intially full of NaNs
for b in np.arange(len(intvl)-1):
for L in np.arange(6):
for i in np.arange(60):
for j in np.arange(141):
B[b,L,i,j] = np.nanmean(A[intvl_cs[b]:intvl_cs[b+1],L,i,j])