2
votes

In order to get a numpy array from a list I make the following:

np.array([i for i in range(0, 12)])

And get:

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

Then I would like to make a (4,3) matrix from this array:

np.array([i for i in range(0, 12)]).reshape(4, 3)

and I get the following matrix:

array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

But if I know that I will have 3 * n elements in the initial list how can I reshape my numpy array, because the following code

np.array([i for i in range(0,12)]).reshape(a.shape[0]/3,3)

Results in the error

TypeError: 'float' object cannot be interpreted as an integer
2
int(a.shape[0]/3) should do - Dav2357
a.reshape(-1, 3) is more general - nsaura
@nsaura indeed, you are right - Dav2357
@Dav2357. a.shape[0] // 3 is more elegant if you insist on going down that road. - Mad Physicist

2 Answers

8
votes

First of all, np.array([i for i in range(0, 12)]) is a less elegant way of saying np.arange(12).

Secondly, you can pass -1 to one dimension of reshape (both the function np.reshape and the method np.ndarray.reshape). In your case, if you know the total size is a multiple of 3, do

np.arange(12).reshape(-1, 3)

to get a 4x3 array. From the docs:

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

As a side note, the reason that you get the error is that regular division, even for integers, automatically results in a float in Python 3: type(12 / 3) is float. You can make your original code work by doing a.shape[0] // 3 to use integer division instead. That being said, using -1 is much more convenient.

0
votes

You can use -1 in .reshape. If you specify one dimension, Numpy will determine the other dimension automatically when possible[1].

np.array([i for i in range(0,12)]).reshape(-1, 3)

[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html