【发布时间】:2018-06-07 15:05:21
【问题描述】:
为了从 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 个元素,我该如何重塑我的 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
【问题讨论】:
-
int(a.shape[0]/3)应该这样做 -
a.reshape(-1, 3) 更通用
-
@nsaura 确实,你是对的
-
@Dav2357。如果你坚持走这条路,
a.shape[0] // 3会更优雅。