0

Although I have tried np.reshape and transpose, I am not getting the desired output.

I have a numpy array that looks like this:

>>> a = np.array([[1, 1, 2, 2],[1, 1, 2, 2],[1, 1, 2,2]])
>>> a
array([[1, 1, 2, 2],
       [1, 1, 2, 2],
       [1, 1, 2, 2]])

I want the following:

>>> b = np.array([[1, 2],[1,2],[1,2],[1, 2],[1,2],[1,2]])
>>> b
array([[1, 2],
       [1, 2],
       [1, 2],
       [1, 2],
       [1, 2],
       [1, 2]])

The best I can do is in four lines of code:

e, f = np.hsplit(a,2)
e = e.reshape(np.size(e))
f = f.reshape(np.size(f))
b = np.vstack((e,f)).T

Can someone provide me with the pythonic way to reshape an array in this manner?

1
  • 1
    Would b = np.reshape(a,(6,2),'F') be enough? Commented Jan 27, 2016 at 21:47

1 Answer 1

1

It is not clear exactly what you are looking for by only using 1s and 2s in the example. Please use letters or unique numbers so the mapping is clearer.

I was able to do some jiggling to make it work but I'm not 100% if this is the mapping you want. See the steps below:

>>> a = np.array([[1, 1, 2, 2],[1, 1, 2, 2],[1, 1, 2,2]])

array([[1, 1, 2, 2],
       [1, 1, 2, 2],
       [1, 1, 2, 2]])


>>> a.reshape(6,2)

array([[1, 1],
       [2, 2],
       [1, 1],
       [2, 2],
       [1, 1],
       [2, 2]])

>>> a.reshape(6,2).transpose()

array([[1, 2, 1, 2, 1, 2],
       [1, 2, 1, 2, 1, 2]])

>>> a.reshape(6,2).transpose().reshape(6,2)

array([[1, 2],
       [1, 2],
       [1, 2],
       [1, 2],
       [1, 2],
       [1, 2]])
Sign up to request clarification or add additional context in comments.

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.