Home > database >  Creating numpy array with a specific pattern
Creating numpy array with a specific pattern

Time:11-03

I'm trying to create a numpy array of intergers ascending intergers (1,2,3,...), such that the n is repeated n times. For example for maximum number 4 I would like

my_arr = [1,2,2,3,3,3,4,4,4,4]

Now this is easy using a for loop

my_arr = numpy.array([])
max = 4
for i in range(1,max   1):
    my_arr = numpy.append(my_arr,np.ones(i)*i)

but this gets horribly slow for large numbers max. Any suggestions?

CodePudding user response:

Use np.repeat:

import numpy as np

def pattern(n):
    x = np.arange(1, n   1)
    return np.repeat(x, x)

# >>> pattern(4)
# array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])

CodePudding user response:

There is a builtin way to do this.

import numpy as np


def builtinway(maxval=10):
    arr = list(range(1, maxval 1))
    return np.repeat(arr, arr)

One way to do this pretty quickly and directly would be as follows. In practice, space would become a problem before the number of operations grows too quickly. (Though in practice, you probably wouldn't do this).

def make_arr(maxval=10):
    arrlen = maxval * (maxval   1) // 2
    arr = np.ones(arrlen)
    for i in range(2, maxval 1):
        addend = np.ones(arrlen)
        addend[:i*(i-1) // 2] = 0
        arr  = addend
    return arr
  • Related