use*_*747 3 python arrays numpy slice
根据 numpy 文档,take\nit 与 \xe2\x80\x9cfancy\xe2\x80\x9d 索引(使用数组索引数组)执行相同的操作。但是,如果您需要沿给定轴的元素,它会更容易使用。
然而,与“花式”或常规 numpy 索引不同,使用切片作为索引似乎不受支持:
\n\nIn [319]: A = np.arange(20).reshape(4, 5)\n\nIn [320]: A[..., 1:4]\nOut[320]: \narray([[ 1, 2, 3],\n [ 6, 7, 8],\n [11, 12, 13],\n [16, 17, 18]])\n\nIn [321]: np.take(A, slice(1, 4), axis=-1)\nTypeError: long() argument must be a string or a number, not \'slice\'\nRun Code Online (Sandbox Code Playgroud)\n\n使用仅在运行时已知的轴上的切片来索引数组的最佳方法是什么?
\n最有效的方法似乎是A[(slice(None),) * axis + (slice(1, 4),)]:
In [19]: import numpy as np\n ...: x = np.random.normal(0, 1, (50, 50, 50))\n ...: s = slice(10, 20)\n ...: axis = 2\n ...: \n ...: \n\nIn [20]: timeit np.rollaxis(np.rollaxis(x, axis, 0)[s], 0, axis + 1)\n2.32 \xc2\xb5s \xc2\xb1 15.1 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\n\nIn [21]: timeit x.take(np.arange(x.shape[axis])[s], axis)\n28.5 \xc2\xb5s \xc2\xb1 38.2 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 10000 loops each)\n\nIn [22]: timeit x[(slice(None),) * axis + (s,)]\n321 ns \xc2\xb1 0.341 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2334 次 |
| 最近记录: |