Means Of Asymmetric Arrays In Numpy
I have an asymmetric 2d array in numpy, as in some arrays are longer than others, such as: [[1, 2], [1, 2, 3], ...] But numpy doesn't seem to like this: import numpy as np foo = n
Solution 1:
We could use an almost vectorized approach based upon np.add.reduceat
that takes care of the irregular length subarrays, for which we are calculating the average values. np.add.reduceat
sums up elements in those intervals of irregular lengths after getting a 1D
flattened version of the input array with np.concatenate
. Finally, we need to divide the summations by the lengths of those subarrays to get the average values.
Thus, the implementation would look something like this -
lens = np.array(map(len,foo)) # Thanks to @Kasramvd on this!vals = np.concatenate(foo)
shift_idx = np.append(0,lens[:-1].cumsum())
out = np.add.reduceat(vals,shift_idx)/lens.astype(float)
Post a Comment for "Means Of Asymmetric Arrays In Numpy"