3

I want to reshape one array using other array.

Say I have array_1, whose shape is (5, 1), e.g.:

>>> array_1
array([[ 0.33333333],
       [ 0.36666667],
       [ 0.16666667],
       [ 0.06666667],
       [ 0.06666667]]

and array_2, whose shape is (1, 5). I want to reshape array_1 so that it gets the shape of array_2. The shape of array_2 can change every time I run the code.

7
  • Are these numpy arrays ? Commented Jul 21, 2015 at 9:50
  • yes.i have added an example array in the question. Commented Jul 21, 2015 at 9:52
  • @AnandSKumar thanks for undoing that work... Commented Jul 21, 2015 at 9:54
  • @jonrsharpe sorry but had to roll back because the example got removed. Commented Jul 21, 2015 at 9:56
  • @AnandSKumar no, you didn't; you could have done what I just did, i.e. edit the example into the improved post Commented Jul 21, 2015 at 9:56

2 Answers 2

5

Assuming numpy arrays, just use array_1.reshape(array_2.shape):

>>> import numpy as np
>>> arr1 = np.arange(5).reshape(5, 1)
>>> arr2 = np.arange(5, 10).reshape(1, 5)
>>> arr1
array([[0],
       [1],
       [2],
       [3],
       [4]])
>>> arr2
array([[5, 6, 7, 8, 9]])
>>> arr1.reshape(arr2.shape)
array([[0, 1, 2, 3, 4]])
>>> arr2.reshape(arr1.shape)
array([[5],
       [6],
       [7],
       [8],
       [9]])

Note that this is not in-place; it creates a new array, so you would need to assign e.g. array_1 = array_1.reshape(...).

Sign up to request clarification or add additional context in comments.

Comments

2

You simply should use numpy.transpose in this case:

import numpy as np

array_1 = [[ 0.33333333],
 [ 0.36666667],
 [ 0.16666667],
 [ 0.06666667],
 [ 0.06666667]]

print "Shape of original array_1: ", np.shape(array_1)

array_1 = np.transpose(array_1)

print array_1
print "Shape of transposed array_1: ", np.shape(array_1)

Output:

Shape of original array_1:  (5, 1)
[[ 0.33333333  0.36666667  0.16666667  0.06666667  0.06666667]]
Shape of transposed array_1:  (1, 5)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.