如何反转 numpy 数组中具有特定大小的每个切片

How to reverse each slice with specific size in a numpy array

我有一个一维数组,其元素为 1 或 0。查看每个 8 个元素的块,我想颠倒块中元素的顺序但保持块的顺序不变。例如,假设我们有一个由两个块组成的数组 A:

A = [0,1,0,0,1,0,1,1,0,1,1,1,0,0,1,0]

经过这个操作,需要变成这样:

A = [1,1,0,1,0,0,1,0,0,1,0,0,1,1,1,0]

我目前有这个解决方案:

A.reshape(-1,8)[:,::-1].reshape(-1)

由于我要对许多大型一维数组执行此操作,因此我想尽可能高效地执行此操作。

是否有更有效的解决方案(比如只使用一种 reshape 方法)?

通过用 ravel:

替换第二个重塑,我获得了最小的加速
In [1]: A = np.asarray([1,1,0,1,0,0,1,0,0,1,0,0,1,1,1,0])

In [2]: %timeit -r 1000 -n 1000 A.reshape(-1,8)[:,::-1].reshape(-1)
2.12 µs ± 427 ns per loop (mean ± std. dev. of 1000 runs, 1000 loops each)

In [3]: %timeit -r 1000 -n 1000 A.reshape(-1,8)[:,::-1].ravel()
1.47 µs ± 362 ns per loop (mean ± std. dev. of 1000 runs, 1000 loops each)

我还假设使用 flip 会进一步提高效率,但(奇怪的是)这似乎不是真的:

In [4]: %timeit -r 1000 -n 1000 np.flip(A.reshape(-1, 8), 1).ravel()
2.39 µs ± 531 ns per loop (mean ± std. dev. of 1000 runs, 1000 loops each)

编辑:

对于大型数组,效率似乎是相反的:

In [1]: A = np.random.randint(2, size=2**20)

In [2]: %timeit -r 100 -n 100 A.reshape(-1,8)[:,::-1].reshape(-1)
1.01 ms ± 13.4 µs per loop (mean ± std. dev. of 100 runs, 100 loops each)

In [3]: %timeit -r 100 -n 100 A.reshape(-1,8)[:,::-1].ravel()
1.11 ms ± 10.5 µs per loop (mean ± std. dev. of 100 runs, 100 loops each)

In [4]: %timeit -r 100 -n 100 np.flip(A.reshape(-1, 8), 1).ravel()
1.11 ms ± 10.3 µs per loop (mean ± std. dev. of 100 runs, 100 loops each)