如何按列的绝对值对numpy数组进行排序?

Ale*_*han 5 python csv numpy python-3.x

我现在所拥有的:

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")
Run Code Online (Sandbox Code Playgroud)

我想:

  • 3) 的解决方案:能够将这个新的“abs”列添加到原始 ndarray 或
  • 另一种能够按列的绝对值对 csv 文件进行排序的方法。

Isr*_*man 4

这是一种方法。
首先,让我们创建一个示例数组:

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]])
Run Code Online (Sandbox Code Playgroud)

好吧,让我们说

In [41]: col = 1
Run Code Online (Sandbox Code Playgroud)

这是我们想要排序的列,
这里是排序代码 - 使用 Python 的sorted

In [42]: b = sorted(a, key=lambda row: np.abs(row[col]))
Run Code Online (Sandbox Code Playgroud)

让我们将 b 从列表转换为数组,我们有:

In [43]: np.array(b)
Out[43]: 
array([[ 0,  1,  2],
       [-3, -2, -1],
       [ 3,  4,  5],
       [-6, -5, -4]])
Run Code Online (Sandbox Code Playgroud)


这是根据第 1 列的绝对值对行进行排序的数组。