【问题标题】:Most efficient way to roll each column in a numpy array by x steps将 numpy 数组中的每一列滚动 x 步的最有效方法
【发布时间】:2018-05-20 17:06:24
【问题描述】:

我有一个保存数据的二维数组,如下图所示。 每列需要汇总与列索引相同的步数。我怎样才能最理想地做到这一点?我正在考虑一个 for 循环,在其中迭代列,将它们滚动 i,然后将数组的列应用于此滚动结果。

有没有更有效的方法?

【问题讨论】:

  • 我需要了解为什么这被否决了吗?如果我提出问题的方式有问题,我会更新它。

标签: python arrays sorting numpy


【解决方案1】:

你可以像这样使用重塑:

>>> a = np.r_[np.tril(np.random.randint(1, 10, (10, 10))), np.random.randint(1, 10, (5, 10))]
>>> a
array([[7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [9, 4, 0, 0, 0, 0, 0, 0, 0, 0],
       [5, 3, 6, 0, 0, 0, 0, 0, 0, 0],
       [7, 2, 8, 2, 0, 0, 0, 0, 0, 0],
       [6, 1, 3, 6, 5, 0, 0, 0, 0, 0],
       [7, 4, 1, 2, 9, 8, 0, 0, 0, 0],
       [2, 9, 7, 3, 7, 7, 4, 0, 0, 0],
       [2, 4, 2, 9, 1, 6, 8, 8, 0, 0],
       [8, 5, 4, 5, 2, 6, 5, 5, 8, 0],
       [9, 3, 4, 6, 1, 4, 8, 3, 9, 1],
       [3, 7, 7, 7, 3, 7, 9, 8, 2, 1],
       [8, 1, 2, 6, 3, 1, 4, 8, 7, 8],
       [5, 8, 4, 6, 1, 1, 9, 7, 5, 6],
       [7, 3, 9, 9, 1, 1, 3, 4, 8, 1],
       [4, 7, 7, 5, 7, 9, 4, 8, 2, 7]])
>>> 
>>> m, n = a.shape
>>> buffer = np.zeros((m+1, n), dtype=a.dtype, order='F')
>>> buffer.ravel(order='F')[:m*n].reshape(m, n, order='F')[...] = a
>>> result = buffer[:-1]
>>> result
array([[7, 4, 6, 2, 5, 8, 4, 8, 8, 1],
       [9, 3, 8, 6, 9, 7, 8, 5, 9, 1],
       [5, 2, 3, 2, 7, 6, 5, 3, 2, 8],
       [7, 1, 1, 3, 1, 6, 8, 8, 7, 6],
       [6, 4, 7, 9, 2, 4, 9, 8, 5, 1],
       [7, 9, 2, 5, 1, 7, 4, 7, 8, 7],
       [2, 4, 4, 6, 3, 1, 9, 4, 2, 0],
       [2, 5, 4, 7, 3, 1, 3, 8, 0, 0],
       [8, 3, 7, 6, 1, 1, 4, 0, 0, 0],
       [9, 7, 2, 6, 1, 9, 0, 0, 0, 0],
       [3, 1, 4, 9, 7, 0, 0, 0, 0, 0],
       [8, 8, 9, 5, 0, 0, 0, 0, 0, 0],
       [5, 3, 7, 0, 0, 0, 0, 0, 0, 0],
       [7, 7, 0, 0, 0, 0, 0, 0, 0, 0],
       [4, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

【讨论】:

  • 这太棒了。
  • @unutbu 高度赞扬,确实。非常感谢!
  • 这可能是执行此操作的最佳方式。我找到了一种更优雅的编写方式,但不幸的是 realloc 可能会产生另一个副本.. b = a.copy('F'); b.resize(m+1, n); result = b[:-1]
猜你喜欢
  • 1970-01-01
  • 2011-10-09
  • 2022-12-07
  • 2016-08-11
  • 2014-01-02
  • 2020-11-03
  • 2020-09-14
  • 2015-06-12
  • 1970-01-01
相关资源
最近更新 更多