John Saraceno
John Saraceno

Reputation: 239

Reshape a numpy array

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?

Upvotes: 0

Views: 211

Answers (1)

James McCormac
James McCormac

Reputation: 1695

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]])

Upvotes: 1

Related Questions