Means of asymmetric arrays in numpy
<p>I have an asymmetric 2d array in numpy, as in some arrays are longer than others, such as: <code>[[1, 2], [1, 2, 3], ...]</code></p>

<p>But numpy doesn't seem to like this:</p>

<pre><code>import numpy as np

foo = np.array([[1], [1, 2]])
foo.mean(axis=1)
</code></pre>

<p>Traceback:</p>

<pre><code>Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "/home/tom/.virtualenvs/nlp/lib/python3.5/site-packages/numpy/core/_methods.py", line 56, in _mean
    rcount = _count_reduce_items(arr, axis)
  File "/home/tom/.virtualenvs/nlp/lib/python3.5/site-packages/numpy/core/_methods.py", line 50, in _count_reduce_items
    items *= arr.shape[ax]
IndexError: tuple index out of range
</code></pre>

<p>Is there a nice way to do this or should I just do the maths myself?</p>

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

<pre><code>mean_foo = np.array( [np.mean(subfoo) for subfoo in foo] )
</code></pre>

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

<pre><code>mean_foo = np.array( map(np.mean, foo) )
</code></pre>

python numpy