Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a array of consecutive numbers array in numpy?

I'm looking to generate an array as follows:

array([[ 1,  2],
       [ 2,  3],
       [ 3,  4],
       [ 4,  5],
       [ 5,  6],
       [ 6,  7],
       [ 7,  8],
       [ 8,  9],
       [ 9, 10]])

Here is how I generate in NumPy:

import numpy as np
a = np.arange(1, 10)
b = np.arange(2, 11)
np.stack((a, b), axis=1)

Is there any function in NumPy that does this directly?

like image 816
Abbas Avatar asked May 12 '26 13:05

Abbas


1 Answers

The shortest answer I can think of, using broadcasting black magic:

# Solution 1:
np.r_[:9][:,None]+[1,2]
# Solution 2:
np.r_['c',:9]+[1,2]

Or also using np.r_ but without broadcasting this time:

# Solution 3:
np.r_['1,2,0', :10, 1:11]

Every solution produce, as expected:

array([[ 1,  2],
       [ 2,  3],
       [ 3,  4],
       [ 4,  5],
       [ 5,  6],
       [ 6,  7],
       [ 7,  8],
       [ 8,  9],
       [ 9, 10]])
like image 127
obchardon Avatar answered May 15 '26 03:05

obchardon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!