How can I apply a function to a single row or column of a matrix using numpy and python
<p>I am learning numpy and using python and asking for help. I would like to sort a SINGLE row or column as a learning experience. Looking through their docs i see apply_along_axis but there isnt a parameter in their docs on how to indicate a splice/selector in choosing which rows or columns to apply it to.</p>

<p>I only want the second row to be sorted.
Here is my code so far...</p>

<pre><code>import numpy as np
A = [29,-11,10,-160,61,-55,55,-21,19]
A = np.asarray(A)
A = np.reshape(A, (3,-1))
np.apply_along_axis(func1d=sorted, axis=1, arr=A) #this line is not correct
</code></pre>

<p>Starting with the following array...</p>

<pre><code>array([[  29,  -11,   10],
       [-160,   61,  -55],
       [  55,  -21,   19]])
</code></pre>

<p>I would like to see the following output...</p>

<pre><code>array([[ 29,   -11,   10],
       [-160,  -55,   61],
       [ 55,   -21,   19]])
</code></pre>

<p>There's an inplace sort method.</p>

<pre><code>In [75]: A=np.array(A).reshape(3,-1)
In [76]: A
Out[76]: 
array([[  29,  -11,   10],
       [-160,   61,  -55],
       [  55,  -21,   19]])
In [77]: A[1,:].sort()
In [78]: A
Out[78]: 
array([[  29,  -11,   10],
       [-160,  -55,   61],
       [  55,  -21,   19]])
</code></pre>

<p>I just took a guess that it would work on a single row of the array, and tried.  It appears to work.  (I overlooked Divakar's comment).</p>

<p><code>apply_along...</code> and <code>apply_over...</code> are convenience functions that make it easier (not faster) to iterate over one or more dimensions, and over kill in a case like this.</p>

<p>It may be easier to understand this with the <code>np.sort</code> function:</p>

<pre><code>In [85]: np.sort(A[1,:])
Out[85]: array([-160,  -55,   61])
</code></pre>

<p>the function returns a copy of the row that is sorted; we can then write it back to <code>A</code> with:</p>

<pre><code>In [86]: A[1,:]=np.sort(A[1,:])
</code></pre>

<p><code>numpy</code> has its own sorting methods, so usually we don't need to use the general Python list versions, such as <code>sorted</code>.  However this works: <code>A[1,:]=sorted(A[1,:])</code>.</p>

python numpy