How to sort numpy array by absolute value of a column?
<p>What I have now:</p>

<pre><code>import numpy as np
# 1) Read CSV with headers
data = np.genfromtxt("big.csv", delimiter=',', names=True)
# 2) Get absolute values for column in a new ndarray
new_ndarray = np.absolute(data["target_column_name"])
# 3) Append column in new_ndarray to data
# I'm having trouble here. Can't get hstack, concatenate, append, etc; to work
# 4) Sort by new column and obtain a new ndarray
data.sort(order="target_column_name_abs")
</code></pre>

<p>I would like:</p>

<ul>
<li>A solution for 3): To be able to add this new "abs" column to the original ndarray or</li>
<li>Another approach to be able to sort a csv file by the absolute values of a column.</li>
</ul>

<p>Here is a way to do it.<br>
First, let's create a sample array:</p>

<pre><code>In [39]: a = (np.arange(12).reshape(4, 3) - 6)

In [40]: a
Out[40]: 
array([[-6, -5, -4],
       [-3, -2, -1],
       [ 0,  1,  2],
       [ 3,  4,  5]])
</code></pre>

<p>Ok, lets say </p>

<pre><code>In [41]: col = 1
</code></pre>

<p>which is the column we want to sort by,<br>
and here is the sorting code - using Python's <code>sorted</code>:</p>

<pre><code>In [42]: b = sorted(a, key=lambda row: np.abs(row[col]))
</code></pre>

<p>Let's convert b from list to array, and we have:</p>

<pre><code>In [43]: np.array(b)
Out[43]: 
array([[ 0,  1,  2],
       [-3, -2, -1],
       [ 3,  4,  5],
       [-6, -5, -4]])
</code></pre>

<p>Which is the array with the rows sorted according to<br>
the absolute value of column 1.</p>

python python-3.x csv numpy