我现在拥有的:
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")
我愿意:
- 3 的解决方案):为了能够将这个新的“abs”列添加到原始的 ndarray 或
- 另一种能够按列的绝对值对 csv 文件进行排序的方法。
最佳答案
这里有一个方法。
首先,让我们创建一个示例数组:
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]])
好吧,让我们说
In [41]: col = 1
这是我们要排序的列,
这是排序代码 - 使用 Python 的 sorted
:
In [42]: b = sorted(a, key=lambda row: np.abs(row[col]))
让我们将 b 从列表转换为数组,我们有:
In [43]: np.array(b)
Out[43]:
array([[ 0, 1, 2],
[-3, -2, -1],
[ 3, 4, 5],
[-6, -5, -4]])
哪个是行按照
排序的数组
第 1 列的绝对值。
关于python - 如何按列的绝对值对numpy数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39153007/