5

Say you want to create a 2D numpy array, and want to populate it with sequential integers. What are the options available?

Example:

import numpy
a=numpy.array([[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]])

In this case of course I could use range(15) to determine the upper boundary, but how to tell numpy to create a new row after 5 values? I am looking for a general solution, as my real problem revolves around a 2D array with 466 columns and 365 rows.

FaCoffee
  • 7,609
  • 28
  • 99
  • 174
  • 4
    You can do `a = np.arange(15).reshape(3,5)` for your simple example, for the general case `a = np.arange(466*365).reshape(466,365)` should work – EdChum Feb 02 '17 at 14:28

1 Answers1

13

Just use .reshape on a normal np.arange call, which will simply reshape your array without changing its data.

In[101]: np.arange(15).reshape(3, 5)
Out[101]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In[102]: np.arange(466*365).reshape(466, 365)
Out[102]: 
array([[     0,      1,      2, ...,    362,    363,    364],
       [   365,    366,    367, ...,    727,    728,    729],
       [   730,    731,    732, ...,   1092,   1093,   1094],
       ..., 
       [168995, 168996, 168997, ..., 169357, 169358, 169359],
       [169360, 169361, 169362, ..., 169722, 169723, 169724],
       [169725, 169726, 169727, ..., 170087, 170088, 170089]])
miradulo
  • 28,857
  • 6
  • 80
  • 93