Reshape numpy array having only one dimension

佐手、 提交于 2020-07-03 04:35:09

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/50744554/reshape-numpy-array-having-only-one-dimension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!