基于最后一列值的numpy排序数组

时间:2018-06-15 16:23:18

标签: python numpy

import numpy as np

a = np.array([[5,9,44],
              [5,12,43],
              [5,33,11]])

b = np.sort(a,axis=0)

print(b) #not well

# [[ 5  9 11]
# [ 5 12 43]
# [ 5 33 44]]

#desired output:

#[[5,33,11],
# [5,12,43],
# [5,9,44]]

它是什么numpy sort它完全改变行(当然是基于从低到高),但我想保持行不变。我想根据最后一列值对行进行排序,但数组中的行和值必须保持不变。有没有pythonic方式来做到这一点? 感谢

2 个答案:

答案 0 :(得分:5)

ind=np.argsort(a[:,-1])
b=a[ind]

修改 在排序中使用axis时,它会单独对每个列进行排序,您想要的是从所选列中获取已排序行的索引(-1等于最后一列),然后重新排序原始数组

答案 1 :(得分:2)

<select name="subcategory" id="subcategory" disabled="disabled">
    <option value="0">Choisissez une sous-catégorie</option>
</select>

var subCategoriesNames = ['Tout', ['Tout', 'Musiques', 'Concerts', 'Comédies'], ['Tout', 'Films', 'Séries TV', 'Emissions TV', 'Documentaires', 'Animations', 'Animations Séries', 'Concerts', 'Sports'], ['Tout', 'Livres', 'Magazines', 'Presses', 'Mangas', 'BD'], ['Tout', 'Formations', 'Android', 'Windows', 'Linux', 'Web', 'Emulateurs'], ['Tout', 'Android', 'Windows', 'Consoles', 'Linux']],
subCategoriesIds = ['1', ['2', '3', '4', '5'], ['6', '7', '8', '9', '10', '11', '12', '13', '14'], ['15', '16', '17', '18', '19', '20'], ['21', '22', '23', '24', '25', '26', '27'], ['28', '29', '30', '31', '32']],
idx = 0,
subsName;

$(document).ready(function(){
    $('#category').on('change', function(){
        idx = this.selectedIndex;
        if(idx > 0){
            $('select#subcategory').attr('disabled', false);
            for(subsName in subCategoriesNames[idx]) $('select#subcategory').append('<option value="'+subCategoriesIds[idx][subsName]+'">'+subCategoriesNames[idx][subsName]+'</option>');
        }else{
            $('select#subcategory').attr('disabled', true);
        }
        var subcatSelectElem = document.querySelectorAll('#subcategory');
        var subcatSelectElem = M.FormSelect.init(subcatSelectElem, {});
    })
});

可能适合你