Sorting arrays in NumPy by column

后端 未结 13 2230
既然无缘
既然无缘 2020-11-22 03:47

How can I sort an array in NumPy by the nth column?

For example,

a = array([[9, 2, 3],
           [4, 5, 6],
           [7, 0, 5]])

13条回答
  •  鱼传尺愫
    2020-11-22 04:15

    In case someone wants to make use of sorting at a critical part of their programs here's a performance comparison for the different proposals:

    import numpy as np
    table = np.random.rand(5000, 10)
    
    %timeit table.view('f8,f8,f8,f8,f8,f8,f8,f8,f8,f8').sort(order=['f9'], axis=0)
    1000 loops, best of 3: 1.88 ms per loop
    
    %timeit table[table[:,9].argsort()]
    10000 loops, best of 3: 180 µs per loop
    
    import pandas as pd
    df = pd.DataFrame(table)
    %timeit df.sort_values(9, ascending=True)
    1000 loops, best of 3: 400 µs per loop
    

    So, it looks like indexing with argsort is the quickest method so far...

提交回复
热议问题