Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - ValueError: cannot reshape array of size 7267 into shape (302,24,1)

I am reshaping a 1D array into 3D using the following. It works fine but it throws an error when x is 7267. I understand that it is not possible to slice an odd number as an int without losing some values. Would appreciate any solution to this.

code

x = 7248
y= 24

A = np.arange(x)
A.reshape(int(x/y),y,1).transpose()

output

array([[[   0,   24,   48, ..., 7176, 7200, 7224],
        [   1,   25,   49, ..., 7177, 7201, 7225],
        [   2,   26,   50, ..., 7178, 7202, 7226],
        ...,
        [  21,   45,   69, ..., 7197, 7221, 7245],
        [  22,   46,   70, ..., 7198, 7222, 7246],
        [  23,   47,   71, ..., 7199, 7223, 7247]]])
question from:https://stackoverflow.com/questions/65837066/reshape-list-with-column-elements

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

1 Answer

0 votes
by (71.8m points)

The key is, of course, that in order to reshape A in this way, it must be that len(A) % y == 0. How you do this depends on how you would like to handle the extra values.

If you are fine to discard some values in order to shape the array, then you can simply truncate A so that len(A) % y == 0.

E.g.

x = 7267
y = 24

A = np.arange(x - x % y)
A.reshape(x // y, y, 1).transpose()

You may also truncate the array using slices.

E.g.

x = 7267
y = 24

A = np.arange(x)

A[:x - x % y].reshape(x // y, y, 1).transpose()

In the case where all the data must be retained, you can pad A with zeros (or some other value), so that len(A) % y == 0.

E.g.

x = 7267
y = 24

A = np.arange(x)
A = np.pad(A, (0, y - x % y), 'constant')
A = A.reshape(A.shape[0] // y, y, 1).transpose()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...