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.

1
  • 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 Commented Feb 2, 2017 at 14:28

1 Answer 1

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]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.