pythonarraysnumpyshiftdolphindb

Is there an equivalent of np.roll() in DolphinDB?


In Python’s NumPy, np.roll() allows shifting array elements along an axis, where elements that roll beyond the last position wrap around to the first (e.g., np.roll([1, 2, 3], 1) → [3, 1, 2]).

I tried DolphinDB’s move() function, but it doesn’t seem to support circular shifting (i.e., elements shifted past the end don’t wrap around to the beginning). Example of what I need:

# Desired behavior (like np.roll):
input = [1, 2, 3, 4, 5]
rolled = roll(input, 2)  # Expected: [4, 5, 1, 2, 3]

What I tried with move():

move([1, 2, 3, 4, 5], 2)  # Returns [,,1,2,3], but I need [4,5,1,2,3]

Does DolphinDB have a built-in function for circular shifting (like np.roll())? If not, what is the most efficient way to implement this (e.g., using vector operations or a custom function)?


Solution

  • As of my knowelage DolphinDB does not have similar functionality which behaves like np.roll(). Even the move() functionality shift the data in linear way by inserting nulls.

    For your use case you can create a custom function like below to shift items.

    def roll(vec, shift):
        n = len(vec)
        shift = shift % n
        return vec[-shift:] + vec[:-shift] if shift else vec
    

    You can use it like below:

    print(roll([1, 2, 3, 4, 5], 2))
    # Outputs: [4, 5, 1, 2, 3]
    

    Refer the working sample attached here