Numpy TypeError:仅长度为1的数组可以转换为Python标量(重塑) [英] Numpy TypeError: only length-1 arrays can be converted to Python scalars (reshape)

查看:566
本文介绍了Numpy TypeError:仅长度为1的数组可以转换为Python标量(重塑)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如果我改变数组的形状,那么我一般不会有问题:

In Python, if I reshape an array, I have no problem in general:

arr1 = np.array([1,2,3,4])
print np.reshape(arr1, (2, 2, 1))

但是当我尝试重塑10240 x 62 numpy ndarray时,我遇到了一个问题:

But I have a problem when I try to reshape a 10240 x 62 numpy ndarray:

a1 = np.reshape(X_train_s, (X_train_s[0], X_train_s[1], 1))

错误是:

...in reshape
    return reshape(newshape, order=order)
TypeError: only length-1 arrays can be converted to Python scalars

ndarray X_train_s包含float32数字.为什么我不能重塑数组?

The ndarray X_train_s contains float32 numbers. Why can't I reshape the array?

推荐答案

您想要X_train_s的第一维和第二维的长度,但是当您这样做时

You wanted the lengths of the first and second dimensions of X_train_s, but when you did

(X_train_s[0], X_train_s[1], 1)

您选择了第一行和第二行整行,而不是第一维和第二维的长度.如果要访问尺寸长度,则应已索引数组的shape:

you took the first and second entire rows, not the lengths of the first and second dimensions. If you wanted to access dimension lengths, you should have indexed the array's shape:

(X_train_s.shape[0], X_train_s.shape[1], 1)

您可能还想考虑将这个额外的长度为1的轴添加到数组的其他方法,例如使用np.newaxis(又称为None)建立索引:

You might also want to consider other ways of adding this extra length-1 axis to the array, such as indexing with np.newaxis (a.k.a. None):

a1 = X_train_s[:, :, np.newaxis]

这篇关于Numpy TypeError:仅长度为1的数组可以转换为Python标量(重塑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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