4

What is the most efficient way to extend an array with its own values up to a specific size?

import numpy as np

# For this example, lets use an array with 4 items
data = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]]) # 4 items

# I want to extend it to 10 items, here's the expected result would be:
data = np.array([[ 0,  1,  2],
                 [ 3,  4,  5],
                 [ 6,  7,  8],
                 [ 9, 10, 11],
                 [ 0,  1,  2],
                 [ 3,  4,  5],
                 [ 6,  7,  8],
                 [ 9, 10, 11],
                 [ 0,  1,  2],
                 [ 3,  4,  5]])

2 Answers 2

3

You can concatenate arrays:

def extend_array(arr, length):
    factor, fraction = divmod(length, len(arr))
    return np.concatenate([arr] * factor + [arr[:fraction]])

>>> extend_array(data, 10)

array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [ 0,  1,  2],
       [ 3,  4,  5]])
Sign up to request clarification or add additional context in comments.

3 Comments

Quick correction, you want arr[:fraction]. Depending on the size of the array, your method can be noticeably faster because the repeated whole chunks are intermediately stored as references to the same object.
awesome! yes the last item should be arr[:fraction]
Corrected. Changed the name and forgot one of them.
2

The most efficient way I can think of is using the itertools module. First create a cycle of each row (infinite iterator) and then fetch as many rows as you need with islice(). The result of this must be a tuple or list, because numpy requires the length of the array to be explicit at construction time.

import itertools as it

def extend_array(arr, length):
    return np.array(tuple(it.islice(it.cycle(arr), length)))

Usage:

>>> data = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
>>> extend_array(data, 10)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [ 0,  1,  2],
       [ 3,  4,  5]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.