python - 对列表的 numpy 数组进行排序

标签 python numpy vectorization

我们得到一个列表 (dtype=object) 的 numpy 数组 (ndarray),并且希望返回一个类似的列表数组,其中每个列表都已排序。有没有一种有效的方法来做到这一点(即没有 for 循环等)?

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

例如:

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

所以 a 是:

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)

最佳答案

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

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 数组元素的最快方法,但它很少比基于列表的迭代更好。

关于python - 对列表的 numpy 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59235248/

相关文章:

python - 如何矢量化 numpy 数组的 2x2 子数组的平均值?

python - 当 Python 从命令行运行时导入 urllib.parse 失败

python - 如何将 numpy.matrix 或数组转换为 scipy 稀疏矩阵

python - 根据 vi 模式更改交互式 IPython 控制台中的光标形状

python - 有什么简单的方法可以在 python 中稀疏地存储具有冗余模式的矩阵?

python - 很难理解为什么这两种矩阵切片方法在 numpy 中并不等效

matlab - 在 MATLAB 中取最大值的连续矩阵 block

python - NumPy 数组索引 4D 数组

python - django 自动填充管理中的 manytomany 字段

python - 关于 python 中线程输出的困惑