title: Apply a function to each row of a ndarray
body: <p>I have this function to calculate squared Mahalanobis distance of vector x to mean:</p>
  
  <pre><code>def mahalanobis_sqdist(x, mean, Sigma):
     '''
      Calculates squared Mahalanobis Distance of vector x 
      to distibutions' mean 
     '''
     Sigma_inv = np.linalg.inv(Sigma)
     xdiff = x - mean
     sqmdist = np.dot(np.dot(xdiff, Sigma_inv), xdiff)
     return sqmdist
  </code></pre>
  
  <p>I have an numpy array that has a shape of <code>(25, 4)</code>. So, I want to apply that function to all 25 rows of my array without a for loop. So, basically, how can I write the vectorized form of this loop:</p>
  
  <pre><code>for r in d1:
      mahalanobis_sqdist(r[0:4], mean1, Sig1)
  </code></pre>
  
  <p>where <code>mean1</code> and <code>Sig1</code> are :</p>
  
  <pre><code>&gt;&gt;&gt; mean1
  array([ 5.028,  3.48 ,  1.46 ,  0.248])
  &gt;&gt;&gt; Sig1 = np.cov(d1[0:25, 0:4].T)
  &gt;&gt;&gt; Sig1
  array([[ 0.16043333,  0.11808333,  0.02408333,  0.01943333],
         [ 0.11808333,  0.13583333,  0.00625   ,  0.02225   ],
         [ 0.02408333,  0.00625   ,  0.03916667,  0.00658333],
         [ 0.01943333,  0.02225   ,  0.00658333,  0.01093333]])
  </code></pre>
  
  <p>I have tried the following but it didn't work:</p>
  
  <pre><code>&gt;&gt;&gt; vecdist = np.vectorize(mahalanobis_sqdist)
  &gt;&gt;&gt; vecdist(d1, mean1, Sig1)
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 1862, in __call__
      theout = self.thefunc(*newargs)
    File "&lt;stdin&gt;", line 6, in mahalanobis_sqdist
    File "/usr/lib/python2.7/dist-packages/numpy/linalg/linalg.py", line 445, in inv
      return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
  IndexError: tuple index out of range
  </code></pre>