python - reshape 只有一维的numpy数组

标签 python numpy reshape

为了从 list 中获取一个 numpy 数组,我做了以下操作:

np.array([i for i in range(0, 12)])

并得到:

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

然后我想从这个数组中创建一个(4,3)矩阵:

np.array([i for i in range(0, 12)]).reshape(4, 3)

我得到以下矩阵:

array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

但是如果我知道我将在初始 list 中有 3 * n 个元素,我该如何 reshape 我的 numpy 数组,因为下面的代码

np.array([i for i in range(0,12)]).reshape(a.shape[0]/3,3)

错误的结果

TypeError: 'float' object cannot be interpreted as an integer

最佳答案

首先,np.array([i for i in range(0, 12)]) 是一种不太优雅的说法 np.arange(12).

其次,您可以将 -1 传递给 reshape 的一维(函数 np.reshape 和方法 np.ndarray.reshape )。在您的情况下,如果您知道总大小是 3 的倍数,则执行

np.arange(12).reshape(-1, 3)

得到一个 4x3 的数组。来自文档:

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

附带说明一下,出现错误的原因是常规除法,即使是整数,在 Python 3 中也会自动生成 float:type(12/3)float。您可以通过执行 a.shape[0]//3 来使用整数除法来使您的原始代码正常工作。也就是说,使用 -1 更方便。

关于python - reshape 只有一维的numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50744554/

相关文章:

python - 有没有办法在不使用组的情况下引用 re.sub 中的整个匹配表达式?

python - 如何为多对多关系(OpenERP7)添加和显示一些属性?

Python:将 numpy 符号数组转换为 int 并返回

python - 将 CIFAR 1d 数组从 pickle 转换为图像 (RGB)

python - PyTorch 3 reshape 错误

python - 在 Python 中将 html 标签添加到 XML.ElementTree 元素的文本

python - django TemplateDoesNotExist 异常但模板存在

python - 使用 gensim 的 Word2vec 训练在 10 万个句子后开始交换

reshape 会抛出 data.table 错误,但不会抛出 data.frame 错误

r - 转置矩阵 R