6

I am new to Python and I am having a bit of trouble with the array functions. I want to make a 4 by 4 array which contains the numbers from 1 to 16.

I know that using np.zeros((4,4)) outputs a 4x4 array with all zeros. Using np.array(range(17)) I can get an array of the required numbers BUT not in the correct shape (4x4).

It must be fairly simple, surely? All comments are much appreciated.

1 Answer 1

9

The problem is that you are creating an array of 17 values (zero through 16), which can't be reshaped to 4x4. Instead:

>>> a = np.arange(1, 17).reshape(4,4)
>>> a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])
Sign up to request clarification or add additional context in comments.

6 Comments

Oh I see, I should have noticed that. So is this the standard way of producing custom arrays?
It depends on how "custom" you want them to be, but it's a very common starting point. arange only gives sequential values (but can start at any number and take steps other than one). reshape works on any array as long as the number of values stack nicely.
It depends on what you mean by custom. There are numerous ways to create and/or initialize an array. If you just want the shape, you can use np.empty, np.empty_like, np.zeros, etc. If you also want to initialize the values, you can call np.fromfunction or others.
I am assuming that "initialising the values" means to make my own values? What would be the process if I want a n-by-m array with a list of numbers (that fit nicely)? I tried the following and it works nicely: 'a=(1,2,4,66,88,99,5,10)' 'b=np.array(a).reshape(4,2)' 'print b' This returns a 4-by-2 array of the desired numbers. Efficient? Or is there a better way. PS: I can't seem to get the hang of this mini-markdown formatting for the code lines. I apologise for that.
By initialize, I mean "set its initial values". What you did is fine.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.