You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Numpy函数组合实现1D数组的多roll操作生成2D数组?

Vectorized Multi-Roll Implementation for NumPy

Absolutely! You can achieve this in a fully vectorized, Numpythonic way by leveraging index broadcasting instead of explicit loops. Here's how:

The Solution Code

import numpy as np

def multiroll(array, rolls):
    """Create multiple rolls of a 1D vector (vectorized implementation)"""
    arr = np.asarray(array)
    m = arr.size
    rolls = np.asarray(rolls)
    # Create a 2D index matrix where each column corresponds to a roll
    indices = (np.arange(m)[:, None] - rolls) % m
    # Index the original array with this matrix to get all rolls at once
    return arr[indices]

How It Works

Let's break down the logic using your example:

  • For an input array np.arange(10) (length m=10) and rolls [-1, 0, 1, 2]:
    1. np.arange(m)[:, None] creates a 10x1 column array of indices: [[0], [1], ..., [9]]
    2. Subtracting the rolls array (shaped (4,)) broadcasts to a 10x4 matrix, where each element (i,j) is i - rolls[j]
    3. Taking modulo m wraps negative indices around to the end of the array, mimicking the behavior of np.roll
    4. Indexing the original array with this 2D index matrix directly produces the desired 10x4 result

Testing Against Your Example

Running:

multiroll(np.arange(10), [-1, 0, 1, 2])

Gives exactly the output you provided:

array([[1, 0, 9, 8],
       [2, 1, 0, 9],
       [3, 2, 1, 0],
       [4, 3, 2, 1],
       [5, 4, 3, 2],
       [6, 5, 4, 3],
       [7, 6, 5, 4],
       [8, 7, 6, 5],
       [9, 8, 7, 6],
       [0, 9, 8, 7]])

Why This Is Better Than Loops

  • Efficiency: Vectorized operations run in optimized C code under the hood, making them far faster for large arrays or many roll values
  • Readability: The code expresses intent clearly without cluttering with loop syntax
  • Maintainability: Fewer lines mean fewer opportunities for bugs

Alternative Approaches (Less Ideal)

While you could use np.tile or np.repeat to create a larger array and slice it, the index broadcasting method is more direct and memory-efficient. For example, tiling the array twice would require storing a 10x20 array, whereas the index method only creates a 10x4 integer matrix (a much smaller footprint).

内容的提问来源于stack exchange,提问作者MikeRand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:37:51