ValueError: cannot reshape array of size 7267 into shape (302,24,1)
ValueError: cannot reshape array of size 7267 into shape (302,24,1)
我正在使用以下方法将 1D 阵列重塑为 3D。它工作正常,但当 x
为 7267 时会抛出错误。我知道不可能在不丢失某些值的情况下将奇数切片为 int。对此有任何解决方案将不胜感激。
代码
x = 7248
y= 24
A = np.arange(x)
A.reshape(int(x/y),y,1).transpose()
输出
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]]])
当然关键是,要这样重塑A
,就必须是len(A) % y == 0
。如何执行此操作取决于您希望如何处理额外的值。
如果您可以丢弃一些值以调整数组的形状,那么您可以简单地 truncate A
以便 len(A) % y == 0
.
例如
x = 7267
y = 24
A = np.arange(x - x % y)
A.reshape(x // y, y, 1).transpose()
您也可以使用切片截断数组。
例如
x = 7267
y = 24
A = np.arange(x)
A[:x - x % y].reshape(x // y, y, 1).transpose()
在必须保留所有数据的情况下,您可以填充 A
零(或其他一些值),以便len(A) % y == 0
.
例如
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()
我正在使用以下方法将 1D 阵列重塑为 3D。它工作正常,但当 x
为 7267 时会抛出错误。我知道不可能在不丢失某些值的情况下将奇数切片为 int。对此有任何解决方案将不胜感激。
代码
x = 7248
y= 24
A = np.arange(x)
A.reshape(int(x/y),y,1).transpose()
输出
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]]])
当然关键是,要这样重塑A
,就必须是len(A) % y == 0
。如何执行此操作取决于您希望如何处理额外的值。
如果您可以丢弃一些值以调整数组的形状,那么您可以简单地 truncate A
以便 len(A) % y == 0
.
例如
x = 7267
y = 24
A = np.arange(x - x % y)
A.reshape(x // y, y, 1).transpose()
您也可以使用切片截断数组。
例如
x = 7267
y = 24
A = np.arange(x)
A[:x - x % y].reshape(x // y, y, 1).transpose()
在必须保留所有数据的情况下,您可以填充 A
零(或其他一些值),以便len(A) % y == 0
.
例如
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()