ValueError:无法将大小为7267的数组重塑为形状(302,24,1) [英] ValueError: cannot reshape array of size 7267 into shape (302,24,1)

查看:183
本文介绍了ValueError:无法将大小为7267的数组重塑为形状(302,24,1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下方法将1D数组重塑为3D.它可以正常工作,但是当 x 为7267时会引发错误.我知道在不丢失某些值的情况下,无法将奇数切片为int.希望对此有任何解决方案.

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.

代码

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 .如何执行取决于您希望如何处理额外的值.

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.

如果可以舍弃某些值以整形数组,则可以简单地截短 A ,以便 len(A)%y == 0 .

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.

例如

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.

例如

x = 7267
y = 24

A = np.arange(x)

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

在必须保留所有数据的情况下,可以用零(或其他一些值) pad A ,从而使 len(A)%y == 0 .

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.

例如

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()

这篇关于ValueError:无法将大小为7267的数组重塑为形状(302,24,1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆