【发布时间】:2021-09-26 13:10:45
【问题描述】:
我得到一个 ndarray 从文件中读取它,像这样
my_data = np.genfromtxt(input_file, delimiter='\t', skip_header=0)
示例输入(已解析)
[[ 2. 1. 2. 0.]
[ 2. 2. 100. 0.]
[ 2. 3. 100. 0.]
[ 3. 1. 2. 0.]
[ 3. 2. 4. 0.]
[ 3. 3. 6. 0.]
[ 4. 1. 2. 0.]
[ 4. 2. 4. 0.]
[ 4. 3. 6. 0.]]
更长的example input(未解析)。
前两列应该是int,而最后两列应该是float,但这就是我得到的。欢迎提出建议。
主要问题是,我正在尝试使用 Numpy 对其进行排序,以便对行进行排序,优先考虑第二列上的数字,然后是第一列上的数字。
所需输出示例
[[ 2. 1. 2. 0.]
[ 3. 1. 2. 0.]
[ 4. 1. 2. 0.]
[ 2. 2. 100. 0.]
[ 3. 2. 4. 0.]
[ 4. 2. 4. 0.]
[ 2. 3. 100. 0.]
[ 3. 3. 6. 0.]
[ 4. 3. 6. 0.]]
我知道this answer,它适用于对单列上的行进行排序。
我尝试对第二列进行排序,因为第一列已经排序,但这还不够。有时,第一列也会被重新排序,非常糟糕。
new_data = my_data[my_data[:, 1].argsort()]
print(new_data)
#output
[[ 2. 1. 2. 0.]
[ 4. 1. 2. 0.] #ouch
[ 3. 1. 2. 0.] #ouch
[ 2. 2. 100. 0.]
[ 3. 2. 4. 0.]
[ 4. 2. 4. 0.]
[ 2. 3. 100. 0.]
[ 3. 3. 6. 0.]
[ 4. 3. 6. 0.]]
我也查了this question
答案提到
这里的问题是 np.lexsort 或 np.sort 不适用于 dtype 对象的数组。为了解决这个问题,您可以在创建 order_list 之前对 rows_list 进行排序:
import operator
rows_list.sort(key=operator.itemgetter(0,1,2))
但我在sort 类型的ndarray 函数中没有key 参数。在我的情况下,合并字段不是一种选择。
另外,我没有标题,所以,如果我尝试使用 order 参数进行排序,我会收到错误。
ValueError: Cannot specify order when the array has no fields.
我宁愿就地排序或至少获得相同类型的结果ndarray。然后我想把它保存到一个文件中。
如何在不弄乱数据类型的情况下做到这一点?
【问题讨论】:
标签: python arrays sorting numpy