Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

python - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...