3

I am trying to create an array of size 6*n, such that for every batch of 6 cells in the array I will have the following integer values:

a = [n-2, n-1,n,n,n+1,n+1,n+2,n+3]

The banal way that I can think of is using this routine:

a = []
for i in xrange(n):
    np.append(a,[n-2, n-1,n,n,n+1,n+1,n+2,n+3])

But is there a smarter-faster way of doing it?

2
  • 1
    Your example is still broken, which makes it harder to understand exactly what you want. If you want a single list you could use a.extend([n-2, n-1,n,n,n+1,n+1,n+2,n+3]), or if you want nested lists you could use a.append([n-2, n-1,n,n,n+1,n+1,n+2,n+3]) Commented Aug 31, 2015 at 17:34
  • 1
    Are you sure about 6? The length of your pattern is 8. Your code gives an array with length 8*n. And do you mean to have i in your loop or not? Commented Aug 31, 2015 at 18:04

1 Answer 1

5

You can use numpy.tile:

>>> n = 6
>>> arr = np.array([n-2, n-1, n, n, n+1, n+1, n+2, n+3])
>>> np.tile(arr, n)
array([4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8,
       9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7,
       8, 9])
# Reshape to get the desired output
>>> np.tile(arr, n).reshape(n, arr.size)
array([[4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9]])
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think the reshape is needed. OP's example gives a 1d (8*n,) shaped array.

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.