Numpy: average over one dimension in "jagged" 3D array

arrays, jagged-arrays, multidimensional-array, numpy, python

Solution

What about using `np.vectorize`:

do_avg = np.vectorize(np.average)
data_2d = do_avg(data)

Problem

Suppose I have an N*M*X-dimensional array "data", where N and M are fixed, but X is variable for each entry data[n][m]. (Edit: To clarify, I just used np.array() on the 3D python list which I used for reading in the data, so the numpy array is of dimensions N*M and its entries are variable-length lists) I'd now like to compute the average over the X-dimension, so that I'm left with an N*M-dimensional array. Using np.average/mean with the axis-argument doesn't work, so the way I'm doing it right now is just iterating over N and M and appending the manually computed average to a new list, but that just doesn't feel very "python": ``` avgData=[] for n in data: temp=[] for m in n: temp.append(np.average(m)) avgData.append(temp) ``` Am I missing something obvious here? I'm trying to freshen up my python skills while I'm at it, so interesting/varied responses are more than welcome! :) Thanks!

Original source