numpy Python对没有精确平方根的列表进行整形

x33g5p2x  于 2023-01-30  发布在  Python
关注(0)|答案(1)|浏览(135)

我尝试使用numpy.reshape重新整形一个长度为155369的numpy数组,但是由于155369没有精确的平方根,我们将其向下舍入,reforme函数给出错误ValueError: cannot reshape array of size 155369 into shape (394, 394)

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

如何正确地调整这个数组的形状?

jexiocij

jexiocij1#

您需要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]])

相关问题