Home > front end >  Python reshape list that has no exact square root
Python reshape list that has no exact square root

Time:01-27

I'm trying to reshape a numpy array with a length of 155369 using numpy.reshape but since 155369 has no exact square root we round it down and the reshape function gives an error ValueError: cannot reshape array of size 155369 into shape (394, 394)

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

How can this array be reshaped correctly?

CodePudding user response:

You need either to pad your array:

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)

Or to drop extra values:

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

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

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

b.shape
# (394, 394)

Example with a input array of 13 elements:

# 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]])
  • Related