问题
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]]])
回答1:
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()
来源:https://stackoverflow.com/questions/62903819/valueerror-cannot-reshape-array-of-size-7267-into-shape-302-24-1