且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

numpy中不对称数组的均值

更新时间:2022-12-01 14:15:48

我们可以使用基于

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)