1

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?

0

2 Answers 2

4

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

That's clever! Never thought about indices. Thank you so much
1

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

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.