2D numpy数组的形状不正确

时间:2018-08-30 12:29:55

标签: python python-3.x numpy numpy-ndarray

我想创建5x5的numpy数组。声明如下:

aa = np.array([[2.82842712, 2.23606798, 2.0, 2.23606798, 2.82842712],
               [2.23606798, 1.41421356, 1.0, 1.41421356, 2.23606789],
               [2.0,        1.0,        0.0, 1.0,        2.0],
               [2.23606789, 1,41421356, 1.0, 1.41421356, 2.23606789],
               [2.82842712, 2.23606789, 2.0, 2.23606798, 2.82842712]])

但是当我检查它的大小是5x1时。

在控制台数组中打印的样子:

MATRICE aa:
[[2.82842712, 2.23606798, 2.0, 2.23606798, 2.82842712]
 [2.23606798, 1.41421356, 1.0, 1.41421356, 2.23606789]
 [2.0, 1.0, 0.0, 1.0, 2.0]
 [2.23606789, 1, 41421356, 1.0, 1.41421356, 2.23606789]
 [2.82842712, 2.23606789, 2.0, 2.23606798, 2.82842712]]
Shape: (5,)

有人看到我错了吗?

1 个答案:

答案 0 :(得分:5)

您在第四行中有六个元素,假设[2.23606789, 1, 41421356, 1.0, 1.41421356, 2.23606789]更改为1.41421356

import numpy as np

aa = np.array([[2.82842712, 2.23606798, 2.0, 2.23606798, 2.82842712],
               [2.23606798, 1.41421356, 1.0, 1.41421356, 2.23606789],
               [2.0,        1.0,        0.0, 1.0,        2.0],
               [2.23606789, 1.41421356, 1.0, 1.41421356, 2.23606789],
               [2.82842712, 2.23606789, 2.0, 2.23606798, 2.82842712]])



print(aa.shape)

输出

(5, 5)

@FHTMitchell提到numpy仅自动转换矩形矩阵。