Skip to content Skip to sidebar Skip to footer

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)

Solution 2:

You could perform the mean for each sub-array of foo using a list comprehension:

mean_foo = np.array( [np.mean(subfoo) for subfoo in foo] )

As suggested by @Kasramvd in another answer's comment, you can also use the map function :

mean_foo = np.array( map(np.mean, foo) )

Post a Comment for "Means Of Asymmetric Arrays In Numpy"