Extending a numpy array to a specific range with native content

What is the most efficient way to expand an array with its own values ​​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 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]])
+4
source share
2 answers

You can combine 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]])
+3
source

The most efficient way I can think of is to use the itertools module. First, create a cycle of each line (infinite iterator), and then select as many rows as needed islice(). The result should be a tuple or list, because numpy requires the length of the array to be explicit at build time .

import itertools as it

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

Using:

>>> 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]])
+1
source

Source: https://habr.com/ru/post/1625928/


All Articles