将一维数组重塑为矩阵二维矩阵

时间:2019-11-23 04:56:22

标签: python numpy

我想将200行5列的1D数组转换为2D数组,但是我的代码抛出一个错误:ValueError:无法将大小为1的数组重塑为形状(200,5)

import numpy as np
np.random.seed(25)
ar = np.random.randn(1000)
ar = ar * 100
ar = ar.astype('int8')
ar

到这里为止都是不错的选择,但是我想重塑此大小为1000的数组并将其重塑为5列,200行的集合。返回这个新数组,并用它替换原来的ar数组。所以我写了下面的代码,但是重塑不起作用(ValueError:无法将大小为1的数组重塑为形状(200,5)),我的代码怎么了?

def reshape(my_array):
    ar = np.reshape(my_array,(200,5))
    ar

ar = reshape(ar)

1 个答案:

答案 0 :(得分:0)

可能我建议进行此更改。它会起作用,因为我认为您正在向函数传递错误的ar:

import numpy as np
np.random.seed(25)
ar = np.random.randn(1000)
ar = ar * 100
ar = ar.astype('int8')
ar

def reshape(my_array):
    ar = np.reshape(my_array,(200,5))
    return ar

new_ar = reshape(ar)
相关问题