Gul*_*zar 3 python sorting numpy
我有两个排序的 np.arrays,说
1, 2, 3, 5
Run Code Online (Sandbox Code Playgroud)
和
2, 4, 6, 7
Run Code Online (Sandbox Code Playgroud)
我想要
1 2 2 3 4 5 6 7
Run Code Online (Sandbox Code Playgroud)
不想要 python for 循环。
是否有一些 numpy 功能?
奖励:按某些轴对矩阵执行此操作(其他轴具有相同的形状)
导入 sortednp 就可以了:
import numpy as np
import sortednp as s
a = np.array([1,2,3,5])
b = np.array([2,4,6,7])
m = s.merge(a, b)
print(m)
Run Code Online (Sandbox Code Playgroud)
滥用输入数组的排序性质,我们可以使用np.searchsorted,如下所示 -
def merge_sorted_arrays(a, b):\n m,n = len(a), len(b)\n # Get searchsorted indices\n idx = np.searchsorted(a,b)\n\n # Offset each searchsorted indices with ranged array to get new positions\n # of b in output array\n b_pos = np.arange(n) + idx\n\n l = m+n\n mask = np.ones(l,dtype=bool)\n out = np.empty(l,dtype=np.result_type(a,b))\n mask[b_pos] = False\n out[b_pos] = b\n out[mask] = a\n return out\nRun Code Online (Sandbox Code Playgroud)\n\n示例运行(使用重复项的一般情况)-
\n\nIn [52]: a\nOut[52]: array([1, 2, 3, 3, 5, 9, 9, 9])\n\nIn [53]: b\nOut[53]: array([ 2, 4, 6, 6, 6, 7, 10])\n\nIn [54]: merge_sorted_arrays(a, b)\nOut[54]: array([ 1, 2, 2, 3, 3, 4, 5, 6, 6, 6, 7, 9, 9, 9, 10])\nRun Code Online (Sandbox Code Playgroud)\n\n随机排序1000000大小的数组上的 Timimgs -
针对流行的连接+排序方法进行基准测试。
\n\n# Setup\nIn [141]: np.random.seed(0)\n ...: a = np.sort(np.random.randint(0,1000000,(1000000)))\n ...: b = np.sort(np.random.randint(0,1000000,(1000000)))\n\n# @chmod777's soln\nIn [142]: %%timeit\n ...: c = np.concatenate((a,b), axis=0)\n ...: c.sort()\n141 ms \xc2\xb1 2.13 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\nIn [143]: %timeit merge_sorted_arrays(a, b)\n55.1 ms \xc2\xb1 5.1 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
603 次 |
| 最近记录: |