如何用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)(lengthm=10) and rolls[-1, 0, 1, 2]:np.arange(m)[:, None]creates a 10x1 column array of indices:[[0], [1], ..., [9]]- Subtracting the
rollsarray (shaped (4,)) broadcasts to a 10x4 matrix, where each element(i,j)isi - rolls[j] - Taking modulo
mwraps negative indices around to the end of the array, mimicking the behavior ofnp.roll - 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
相关产品推荐
相关产品推荐

