Sarang Manjrekar
Sarang Manjrekar

Reputation: 2001

total size of new array must be unchanged

I have two arrays x1 and x2, both are 1*14 arrays i am trying to zip them up and then perform reshape.

The code is as below ;

x1

Out[122]: array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])

x2

Out[123]: array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 1, 3])

X = np.array(zip(x1, x2)).reshape(2, len(x1))

ValueErrorTraceback (most recent call last) in () ----> 1 X = np.array(zip(x1, x2)).reshape(2, len(x1))

ValueError: total size of new array must be unchanged

Upvotes: 2

Views: 7992

Answers (3)

Moses Koledoye
Moses Koledoye

Reputation: 78564

I would assume you're on Python 3, in which the result is an array with a zip object.

You should call list on the zipped items:

X = np.array(list(zip(x1, x2))).reshape(2, len(x1))
#            ^^^^
print(X)
# [[1 1 2 3 3 2 1 2 5 8 6 6 5 7]
#  [5 6 6 7 7 1 8 2 9 1 7 1 9 3]]

In Python 2, zip returns a list and not an iterator as with Python 3, and your previous code would work fine.

Upvotes: 3

holdenweb
holdenweb

Reputation: 37203

np.array isn't recognizing the generator created by zip as an iterable. It works fine if you force conversion to a list first:

from array import array
import numpy as np
x1 = array('i', [1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])
x2 = array('i', [1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 1, 3])
print(np.array(list(zip(x1, x2))).reshape(2, len(x1)))

gives

[[1 1 2 3 3 2 1 2 5 8 6 6 5 7]
 [5 6 6 7 7 1 8 2 9 1 7 1 9 3]]

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96360

You are on Python 3, so zip is evaluated lazily.

>>> np.array(zip(x1,x2))
array(<zip object at 0x7f76d0befe88>, dtype=object)

You need to iterate over it:

>>> np.array(list(zip(x1, x2))).reshape(2, len(x1))
array([[1, 1, 2, 3, 3, 2, 1, 2, 5, 8, 6, 6, 5, 7],
       [5, 6, 6, 7, 7, 1, 8, 2, 9, 1, 7, 1, 9, 3]])

Upvotes: 2

Related Questions