0

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?

1
  • 2
    np.repeat([1, 2, 3, 4], [1, 2, 3, 4]) Commented Nov 2, 2022 at 15:57

2 Answers 2

3

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.