2

Let's say I have got the following numpy array

A = np.array([[0,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]])

out[]: array([[ 0,  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]])

I would like to reorganize it in such a way that the output is

out[] : array([[0,5],
         [1,6],
         [2,7],
         [3,8],
         [4,9],
         [10,15],
         [11,16],
         [12,17],
         [13,18],
         [14,19],
         [20,25],
         [21,26],
         ....,
         [24,29]])

I have been trying different combinations of np.reshape, tranpose, flatten, np.swapaxes, but with no success.

The real array has tens or sometimes hundreds of rows.

Originally, the data is given as DataFrame, but I realized that converting to numpy array could be a better alternative... Can it be done directly using pandas?

4
  • 2
    A.reshape(-1, 2, 5).transpose(0, 2, 1).reshape(-1, 2)? Commented Jan 11, 2023 at 6:45
  • So the first, third, etc. row should be the first column and the second, fourth, etc. row should be the second column? Commented Jan 11, 2023 at 6:45
  • Yes, in general for a, let's say 100x5 dimensional array, I would like to group every 10 rows and put them as columns (this subgroup would be 5x10), then the 10 subgroups are later appended, such that I end up with a 50x10 dimensional array Commented Jan 11, 2023 at 6:58
  • @KelvinTitimbo You can refer this answer for general logic to solve these kind of problems stackoverflow.com/a/47978032/5462372 Commented Jan 11, 2023 at 9:43

1 Answer 1

1

Yes this can be done in this way using as_strided.

from numpy.lib.stride_tricks import as_strided

A = np.array([[0,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]])
A = A.reshape(3, 2, 5)
#print(A)
S = A.itemsize
out = as_strided(A, shape=(3,5,2), strides=(2*A.shape[1]*S ,S, A.shape[1]*S)).copy()
out = out.reshape(15,2)
print(out)
>> [[ 0  5]
 [ 1  6]
 [ 2  7]
 [ 3  8]
 [ 4  9]
 [10 15]
 [11 16]
 [12 17]
 [13 18]
 [14 19]
 [20 25]
 [21 26]
 [22 27]
 [23 28]
 [24 29]]
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.