对 numpy 列表数组进行排序

sort numpy array of lists

我们得到了一个列表 (dtype=object) 的 numpy 数组 (ndarray),并且想要 return 一个类似的列表数组,其中每个列表都已排序。有没有一种有效的方法(即没有 for 循环等)?

请不要提供 np.vectorize() 作为解决方案,因为这是作为 for 循环实现的,因此效率低下。

例如:

a=np.array([[5,4],[6,7,2],[8,1,9]],dtype=object)

所以一个是:

array([list([5, 4]), list([6, 7, 2]), list([8, 1, 9])], dtype=object)

我们希望函数对其进行排序,以便我们得到:

array([list([4, 5]), list([2, 6, 7]), list([1, 8, 9])], dtype=object)
np.array(list(map(sorted, a)))

给出:

array([list([4, 5]), list([2, 6, 7]), list([1, 8, 9])], dtype=object)

您的示例和时间测试的扩展版本:

In [202]: a=np.array([[5,4],[6,7,2],[8,1,9]],dtype=object)                      
In [203]: A = a.repeat(100)                                                     

对每个元素应用 Python 列表排序:

In [204]: np.array([sorted(i) for i in a])                                      
Out[204]: array([list([4, 5]), list([2, 6, 7]), list([1, 8, 9])], dtype=object)

使用 frompyfunc 做同样的事情:

In [205]: np.frompyfunc(sorted,1,1)(a)                                          
Out[205]: array([list([4, 5]), list([2, 6, 7]), list([1, 8, 9])], dtype=object)

一些时间:

In [206]: timeit np.array(list(map(sorted, A)))                                 
168 µs ± 221 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [207]: timeit np.array([sorted(i) for i in A])                               
181 µs ± 249 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

map 比列表理解快一点。我更喜欢理解的可读性。

纯列表版本要快很多:

In [208]: %%timeit temp=A.tolist() 
     ...: list(map(sorted, temp)) 
     ...:  
     ...:                                                                       
88.3 µs ± 70.8 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

frompyfunc比数组映射快,几乎和纯列表版本一样好:

In [209]: timeit np.frompyfunc(sorted,1,1)(A)                                   
97.3 µs ± 1.93 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

这是我以前见过的模式。 frompyfunc 是将函数应用于对象 dtype 数组元素的最快方法,但它很少比基于列表的迭代更好。