Ethan C.
Ethan C.

Reputation: 249

How to split numpy array vertically from any column index

I want to split a numpy array into two subarrays where the splitting point is based on a column id, i.e., vertical split. For instance, if I generate a numpy array of shape [10,16] and I want to create two subarrays by splitting it from the column's index 11, then I should get one subarray of size [10,10] and the other one is from [10,15]. Therefore, I am following numpy.hsplit here but it seems it only does an even split (the subarrays need to be equal). I want to be able to:

  1. Split any numpy array vertically, no matter what is the size of subarrays.
  2. Extract both subarrays.

To simulate my request, the following is my code:

import numpy as np
C = [[1,2,3,4],[5,6,7,8],[9,10,11,12], [13,14,15,16]]
C = np.asarray(C)
C = np.hsplit(C, 3)
print(C)

As you can see, np.hsplit(C, 3) doesn't work unless the splitting generates similar subarrays. Even if I did np.hsplit(C, 2), I don't know how to extract both subarrays into separate numpy arrays.

To achieve my goals, how can I modify this code?

Upvotes: 1

Views: 5010

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You need to specify the indices as list:

import numpy as np

C = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
C = np.asarray(C)

C = np.hsplit(C, [3])

print(C)

Output

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

Upvotes: 1

Tls Chris
Tls Chris

Reputation: 3824

Use the array indexing.

C[:,:3]  # All rows , columns 0 to 2
Out[29]: 
array([[ 1,  2,  3],
       [ 5,  6,  7],
       [ 9, 10, 11],
       [13, 14, 15]])

C[:,3:]  # All rows column 3 (to end in this case also 3).
Out[30]: 
array([[ 4],
       [ 8],
       [12],
       [16]])

Upvotes: 4

Related Questions