1

I am creating this array:

>>> np.array([[0,1,2,3,4,5],[10,11,12,13,14,15],[20,21,22,23,24,25],[30,31,32,33,34,35],[40,41,42,43,44,45],[50,51,52,53,54,55]])

array([[ 0,  1,  2,  3,  4,  5],
       [10, 11, 12, 13, 14, 15],
       [20, 21, 22, 23, 24, 25],
       [30, 31, 32, 33, 34, 35],
       [40, 41, 42, 43, 44, 45],
       [50, 51, 52, 53, 54, 55]])

I am typing all the elements out

2 Answers 2

4

Hm, you could always use a list-comprehension if you already don't mind using an auxiliary list:

>>> np.array([list(range(i, i + 6)) for i in range(0, 55, 10)])
array([[ 0,  1,  2,  3,  4,  5],
       [10, 11, 12, 13, 14, 15],
       [20, 21, 22, 23, 24, 25],
       [30, 31, 32, 33, 34, 35],
       [40, 41, 42, 43, 44, 45],
       [50, 51, 52, 53, 54, 55]])

And here's a numpy way using broadcasting:

>>> np.arange(0, 51, 10).reshape(-1, 1) + np.arange(6)
array([[ 0,  1,  2,  3,  4,  5],
       [10, 11, 12, 13, 14, 15],
       [20, 21, 22, 23, 24, 25],
       [30, 31, 32, 33, 34, 35],
       [40, 41, 42, 43, 44, 45],
       [50, 51, 52, 53, 54, 55]])

This approach, especially for larger examples, will be faster and require much less auxiliary storage.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use an mgrid class instance for this.

import numpy as np

y, x = np.mgrid[:60:10, :6]
a = y + x
print(a)

output

[[ 0  1  2  3  4  5]
 [10 11 12 13 14 15]
 [20 21 22 23 24 25]
 [30 31 32 33 34 35]
 [40 41 42 43 44 45]
 [50 51 52 53 54 55]]

A minor variation is to use the Numpy sum function to perform the addition of the two arrays:

a = np.sum(np.mgrid[:60:10, :6], axis=0)

However, as user2357112 mentions in the comments, it's more efficient to just do the addition with the +operator rather than calling a function.

He also mentions that we can use ogrid to create column and row arrays, which consumes less RAM for y and x. And it's faster too.

import numpy as np
y, x = np.ogrid[:60:10, :6]
a = y + x
print(y, x, a, sep='\n\n')  

output

 [10]
 [20]
 [30]
 [40]
 [50]]

[[0 1 2 3 4 5]]

[[ 0  1  2  3  4  5]
 [10 11 12 13 14 15]
 [20 21 22 23 24 25]
 [30 31 32 33 34 35]
 [40 41 42 43 44 45]
 [50 51 52 53 54 55]]

4 Comments

nice! This is handy.
No point using sum just to add two arrays. (Also, you could use ogrid instead of mgrid to create smaller temporaries. I don't know whether this would be any faster.)
@juanpa.arrivillaga Thanks! mgrid is very handy. But it is slightly weird in that it's a class instance that looks like an array, but it creates the values when you index it.
@user2357112 Thanks, I'll add that info to my answer.

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.