Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python和numpy中,如何通过减少第一列的值对矩阵的行进行排序?_Python_Sorting_Numpy_Matrix - Fatal编程技术网

在Python和numpy中,如何通过减少第一列的值对矩阵的行进行排序?

在Python和numpy中,如何通过减少第一列的值对矩阵的行进行排序?,python,sorting,numpy,matrix,Python,Sorting,Numpy,Matrix,我有一个矩阵,有N=250000行和M=10列。 我想对矩阵进行排序,以减少第一列的值, 所以我写: matrix=np.loadtxt("matrix.dat") np.sort(matrix) matrix=matrix[::-1] 但是np.sort不起作用。事实上,一旦打印排序后的值,我会找到相同的输入矩阵。 有人知道如何解决这个问题吗? 非常感谢这将对矩阵进行排序,以减少第一列的值 import numpy as np # Generate a matrix of data m

我有一个矩阵,有
N=250000行和
M=10列。

我想对矩阵进行排序,以减少第一列的值, 所以我写:

matrix=np.loadtxt("matrix.dat")

np.sort(matrix)

matrix=matrix[::-1]
但是
np.sort
不起作用。事实上,一旦打印排序后的值,我会找到相同的输入矩阵。 有人知道如何解决这个问题吗?
非常感谢

这将对矩阵进行排序,以减少第一列的值

import numpy as np

# Generate a matrix of data
matrix = np.random.rand(5,4)

# Find the ordering of the first column (in increasing order)
ind = np.argsort(matrix[:,0])

# Switch the ordering (so it's decreasing order)
rind = ind[::-1]

# Return the matrix with rows in the specified order
matrix = matrix[rind]
np.sort()
没有对矩阵进行就地排序,您必须将排序后的矩阵分配给上一个变量,或者使用
array.sort(axis=0)
方法进行就地排序。如果希望按降序排列,请反转结果

演示:


“我想对矩阵进行排序,以减少第一列的值”:所以您只想对第一列进行排序?排序后的矩阵=np。排序(矩阵)
In [33]: arr = np.random.rand(5, 4)

In [34]: arr
Out[34]: 
array([[ 0.80270779,  0.14277011,  0.01316072,  0.67149683],
       [ 0.16252499,  0.9969757 ,  0.14759736,  0.24212889],
       [ 0.49493771,  0.51692399,  0.17731137,  0.40797518],
       [ 0.20700147,  0.13279386,  0.2464658 ,  0.9730963 ],
       [ 0.26145694,  0.23410809,  0.78049016,  0.45821089]])

In [35]: arr.sort(0) # or arr.sort(axis=0, kind='mergesort')

In [36]: arr
Out[36]: 
array([[ 0.16252499,  0.13279386,  0.01316072,  0.24212889],
       [ 0.20700147,  0.14277011,  0.14759736,  0.40797518],
       [ 0.26145694,  0.23410809,  0.17731137,  0.45821089],
       [ 0.49493771,  0.51692399,  0.2464658 ,  0.67149683],
       [ 0.80270779,  0.9969757 ,  0.78049016,  0.9730963 ]])

In [37]: arr[::-1]
Out[37]: 
array([[ 0.80270779,  0.9969757 ,  0.78049016,  0.9730963 ],
       [ 0.49493771,  0.51692399,  0.2464658 ,  0.67149683],
       [ 0.26145694,  0.23410809,  0.17731137,  0.45821089],
       [ 0.20700147,  0.14277011,  0.14759736,  0.40797518],
       [ 0.16252499,  0.13279386,  0.01316072,  0.24212889]])