简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM