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

Viewed 233

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?

2 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]])

I don't know of any built-in to do this kind of arrangement, but here are some alternative solutions.

  • Using a half step size and np.floor:

    >>> np.floor(np.arange(1.5, 10.5, .5)).reshape(9, 2)
    
  • Using np.repeat:

    >>> np.repeat(np.arange(1, 11), 2)[1:-1].reshape(9, 2)
    
  • Using np.lib.stride_tricks.as_strided (imo the best method):

    >>> as_strided(np.arange(1, 11), shape=(9, 2), strides=(8, 8))
    

    Since the 2D->1D mapping you're looking to achieve is i + j = k, strides must be (1, 1) in bytes i.e. (8, 8) in bits.

Related