SantoshGupta7
SantoshGupta7

Reputation: 6197

Fastest way to create 2D numpy array which starts at 0, and increases by 1 across the rows, and continues into the columns?

The first element of the first row should start with 0, and increment by 1 across the row, continues incrementing by 1 for the next column, and so on.

This is an example of what I am looking for

array([[0, 1, 2, 3],
       [4, 5, 6, 7],
       [8, 9, 10, 11],
       ...,
       [5231,  5232, 5233,  5234],
       [5235,  5236, 5237, 5238]], dtype=int32)

The solution should be able to apply for any specified 2D dimension, for example

array([[0, 1, 2, ..., 78, 79, 80],
       [81, 82,  83, ..., 158, 159, 160],
       ...,
       [2253, 2254,  2255, ..., 2453, 2454, 2455]], dtype=int32)

The examples aren't numerically accurate, I just wanted to demonstrate that it starts at 0, increments by 1 across the rows , and continues into the next row.

I was thinking of using a for loop to fill each value individually, but I am not sure if that is the fastest solution, nor the most pythonic and programmatically elegant solution.

Upvotes: 0

Views: 575

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53079

You can use

np.arange(nrows*ncols).reshape(nrows,ncols)

Incidentally, this is how 90% of example 2D arrays are created in SO numpy posts.

Upvotes: 3

Wilf Rosenbaum
Wilf Rosenbaum

Reputation: 528

Create a 1D array, initialize the array with the desired values, then use bumpy reshape to convert to a 2D array.

Upvotes: 0

Related Questions