【问题标题】:Python reshape list that has no exact square root没有精确平方根的 Python 重塑列表
【发布时间】:2023-01-26 18:36:23
【问题描述】:

我正在尝试使用numpy.reshape 重塑长度为 15536​​9 的 numpy 数组,但由于 15536​​9 没有精确的平方根,我们将其四舍五入,重塑函数给出了错误ValueError: cannot reshape array of size 155369 into shape (394, 394)

size = int(numpy.sqrt(index))
reshaped = numpy.reshape(data[:index], (size, size))

如何正确地重塑这个数组?

【问题讨论】:

  • 好吧,你不能。想一想如何将 10 个元素的数组重塑为 3x3 矩阵。您有 3 个选择:重塑为 4x4 矩阵并用一些玩具值填充额外的元素。 2)丢弃矩阵中的元素,直到它的大小为 9 或 3)不要重塑为方阵,而是 5x2 矩阵(或更接近正方形的因素的组合)
  • 手动删除其他条目,然后重塑。 Numpy 很智能,它不会让你丢失数据

标签: python numpy


【解决方案1】:

您需要 pad 您的数组:

a = np.ones(155369, dtype=int)

n = int(np.ceil(np.sqrt(a.size)))

b = np.pad(a, (0, n**2-a.size), mode='constant', constant_values=0).reshape(n, n)

b.shape
# (395, 395)

或者删除额外的值:

a = np.ones(155369, dtype=int)

n = int(np.sqrt(a.size))

b = a[:n**2].reshape(n, n)

b.shape
# (394, 394)

包含 13 个元素的输入数组的示例:

# input
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13])

# padding
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13,  0,  0,  0]])

# dropping extra
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 2020-05-25
    • 2023-02-02
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2015-01-11
    相关资源
    最近更新 更多