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

标签 python python-3.x csv numpy

我现在拥有的:

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/

相关文章:

python - 如何删除在上一个日期时间的结束时间之前开始的日期时间

python - 如何从代码自动在 sphinx 中创建顶级文档?

python - 如何使用 python 在 aws s3 预签名的 url 中隐藏我的访问 key

python - 方法调用本身没有方法名?

python-3.x - 将 Scapy L3socket 与 WSL 结合使用时,协议(protocol)不支持地址族

python-3.x - PIL 逊线性系数keras

python - 使用 pandas read_csv 和 nrows 读取 ~13000 行 CSV 文件的部分内容

python-3.x - 遍历图表中的所有可用路径

python - 从字符串创建 Pandas DataFrame

javascript - 在 Javascript 中解析带有可变封闭字符的 CSV 字符串