简体   繁体   中英

Sort rows of matrix based on array

My code try to sort a matrix based on an array, firts i try to sort the array from lowest to highest, the number of elements inside array are directly proportional to the number of rows in the matrix, so when i do bubblesort of the array, i want the same bubblesort in the matrix.

The code sort correctly the array, but the matrix is a mess.

matriz = np.array(([4, 1, 6, 9], [1, 3, 0, 2], [1, 0, 0, 2], [1, 1, 4, 5], [2, 1, 4, 1]))
for i in range(len(matrix)):
    n = int(len(matrix[i]))
    for j in range(n):
        average[i] += (matrix[i][j]/n)

print(average)
for a in range(len(average)-1):
    for b in range(a+1, len(average)):
        if average[a] > average[b]:
            aux = average[a]
            average[a] = average[b]
            average[b] = aux
            auxMatrix = matrix[a]
            matrix[a] = matrix[b]
            matrix[b] = auxMatrix

print(average)
print(matrix)

结果

If you are using numpy you might as well use its efficient functions:

sorted_matrix = matrix[np.argsort(matrix.mean(axis=1))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM