简体   繁体   中英

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.

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.

创建一个1D数组,使用所需的值初始化该数组,然后使用颠簸的整形将其转换为2D数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM