【问题标题】:Reshape 1D array to matrix 2D matrix将一维数组重塑为矩阵二维矩阵
【发布时间】:2020-03-19 03:21:42
【问题描述】:

我想将 1D 数组转换为 200 行 5 列的 2D 数组,但我的代码给我一个错误:ValueError: cannot reshape array of size 1 into shape (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 数组。所以我写了下面的代码,但是reshape不起作用(ValueError: cannot reshape array of size 1 into shape (200,5)),我的代码有什么问题?

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

ar = reshape(ar)

【问题讨论】:

  • 没什么。它似乎工作。虽然您可能应该 return ar

标签: python numpy


【解决方案1】:

我可以建议这个改变。它会起作用,因为我认为您将错误的 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)

【讨论】:

    猜你喜欢
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2016-04-08
    • 2023-04-01
    相关资源
    最近更新 更多