我们得到一个列表 (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/