【问题标题】:How to reverse each slice with specific size in a numpy array如何在numpy数组中反转具有特定大小的每个切片
【发布时间】:2019-01-16 21:49:08
【问题描述】:

我有一个一维数组,其元素为 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 方法)?

【问题讨论】:

  • 我认为这种方法已经相当快了。在我的系统中,将 .reshape(-1) 替换为 .flatten() 会带来一些额外的性能
  • 输入数组的数据类型是什么?

标签: python arrays numpy slice reverse


【解决方案1】:

通过用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)

【讨论】:

  • 既然 OP 提到了large one dimensional arrays,也许用这些来测试一下?
  • .ravel() 稍微提高了性能,但总比没有好。谢谢。 :)
猜你喜欢
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
相关资源
最近更新 更多