Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape numpy array having only one dimension

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
like image 496
Sergei Avatar asked Nov 14 '25 23:11

Sergei


1 Answers

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.

like image 58
Mad Physicist Avatar answered Nov 17 '25 22:11

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!