python - 将 1D 数组 reshape 为矩阵 2D 矩阵

标签 python numpy

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

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

到目前为止都很好,但接下来我想 reshape 这个大小为 1000 的数组,并将该数组 reshape 为 5 列、200 行的集合。返回这个新数组并用它替换原来的 ar 数组。所以我写了下面的代码,但是 reshape 不起作用(ValueError:无法将大小为1的数组 reshape 为形状(200,5)),我的代码有什么问题?

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

ar = reshape(ar)

最佳答案

我可以建议这个改变吗?它会工作,因为我认为你将一个错误的 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)

关于python - 将 1D 数组 reshape 为矩阵 2D 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004646/

相关文章:

python - 是否可以将 bpython 用作完整的调试器?

python - pycompile for python3.2

python - Python 中 numpy 数组和多维列表的区别?

numpy - 最大长度序列的线性自相关不收敛于 Kronecker delta

python - 我在哪里可以找到 numpy.where() 源代码?

python - python中的组合和聚合

python - 如何让redis缓存和mysql的数据保持一致?

python - 隐式函数,希望根据键执行不同的数学函数

python - 平滑逼近 floor 函数以用于反向传播

python - numpy.delete 将 float 组更改为字符串