I know that several questions have been asked about numpy.resize(array, new_size), but it's not doing anything for me. Right now, I have x_array.shape == (1456, 26) and x_array.shape == (1456, 1). I need a way to make their shapes equal. I have tried np.resize(x_array, y_array.shape) but it's not doing anything (no errors, no change). Is it even possible to change the shape like that? Both are numpy.ndarray types. Thank you.
-
I think you're looking for `reshape`. – ForceBru Jun 03 '17 at 18:40
-
reshape gives me this error: "ValueError: cannot reshape array of size 1456 into shape (1456,26)" – SKCSS Jun 03 '17 at 18:43
-
Why do you want to make their shapes equal? To use in an operation? If so, they have a match in one of the axis so this can easily be done. Note that you cannot change from (1456, 1) to (1456, 26) without adding data. However you can add an additional axis to work on. – ayhan Jun 03 '17 at 18:46
-
I am doing regression. there are 26 parameters and 1 represents the target. – SKCSS Jun 03 '17 at 18:52
-
How do you make 26 equal to 1? That doesn't make sense. There are only 2 'reshape' things you can do - throw away 25 of those parameters, or replicate the target 26 times. I doubt if either of those make sense in a regression case. Elaborate on that regression task. – hpaulj Jun 03 '17 at 19:51
2 Answers
np.resize from the docs Return a new array with the specified shape., so x_array will remain (1456, 26).
x_array = np.ones([1456, 26])
print x_array
y_array = np.ones([1456, 1])
print y_array
new_array = np.resize(x_array, y_array.shape)
print new_array
will need to assign resized array to a new array.

- 964
- 6
- 14
While it's technically possible to resize a numpy array with numpy.resize
(see this answer, for example), it's usually much more convenient to use powerful numpy array indexing to achieve the same goal of transforming an ndarray's shape.
So, if your problem is
I need a way to make their shapes equal,
there are two possible solutions:
You want to extend
y_array
. To do that just create a new arrayy_ext
, and copy elements fromy_array
into it:y_ext = numpy.zeros((1456,26)) # y_ext.shape == (1456,26) y_ext[:,0] = y_array[:,0]
You want to trim
x_array
. It's even simpler:x_trimmed = x_array[:,0] # x_trimmed.shape == (1456,) y_trimmed = y_array[:,0] # y_trimmed.shape == (1456,)
Note that in the latter case x_trimmed
shape is (1456,)
, not (1456,1)
. That's why y_array
is "trimmed" too (it becomes 1-dim array), so x_trimmed
and y_trimmed
shapes become truly equal.

- 366
- 3
- 6