5

I have a numpy array of size nxm. I want the number of columns to be limited to k and rest of the columns to be extended in new rows. Following is the scenario -

Initial array: nxm

Final array: pxk

where p = (m/k)*n

Eg. n = 2, m = 6, k = 2

Initial array:

[[1, 2, 3, 4, 5, 6,],
[7, 8, 9, 10, 11, 12]]

Final array:

[[1, 2],
[7, 8],
[3, 4],
[9, 10],
[5, 6],
[11, 12]]

I tried using reshape but not getting the desired result.

2 Answers 2

4

Here's one way to do it

q=array([[1, 2, 3, 4, 5, 6,],
         [7, 8, 9, 10, 11, 12]])
r=q.T.reshape(-1,2,2)
s=r.swapaxes(1,2)
t=s.reshape(-1,2)

as a one liner,

q.T.reshape(-1,2,2).swapaxes(1,2).reshape(-1,2)

array([[ 1,  2],
       [ 7,  8],
       [ 3,  4],
       [ 9, 10],
       [ 5,  6],
       [11, 12]])

EDIT: for the general case, use

q=arange(1,1+n*m).reshape(n,m) #example input
r=q.T.reshape(-1,k,n)
s=r.swapaxes(1,2)
t=s.reshape(-1,k)

one liner is:

q.T.reshape(-1,k,n).swapaxes(1,2).reshape(-1,k)

example for n=3,m=12,k=4

q=array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12],
         [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
         [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]])

result is

array([[ 1,  2,  3,  4],
       [13, 14, 15, 16],
       [25, 26, 27, 28],
       [ 5,  6,  7,  8],
       [17, 18, 19, 20],
       [29, 30, 31, 32],
       [ 9, 10, 11, 12],
       [21, 22, 23, 24],
       [33, 34, 35, 36]])
Sign up to request clarification or add additional context in comments.

Comments

3

Using numpy.vstack and numpy.hsplit:

a = np.array([[1, 2, 3, 4, 5, 6,],
              [7, 8, 9, 10, 11, 12]])
n, m, k = 2, 6, 2
np.vstack(np.hsplit(a, m/k))

result array:

array([[ 1,  2],
       [ 7,  8],
       [ 3,  4],
       [ 9, 10],
       [ 5,  6],
       [11, 12]])

UPDATE As flebool commented, above code is very slow, because hsplit returns a python list, and then vstack reconstructs the final array from a list of arrays.

Here's alternative solution that is much faster.

a.reshape(-1, m/k, k).transpose(1, 0, 2).reshape(-1, k)

or

a.reshape(-1, m/k, k).swapaxes(0, 1).reshape(-1, k)

8 Comments

+1. Notice however that hsplit returns a python list, and then vstack reconstructs the final array from a list of arrays. This is much slower.
@flebool, Thank you for the information. +1 your answer.
Well.. You first posted a wrong answer, then deleted it. Then posted another wrong answer, and deleted it. Finally, you're basically copying my answer. I am downvoting, this is not fair IMHO. sorry.
@flebool, I didn't copy your answer.
@flebool, BTW, I deleted only once.
|

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.