Medo
Medo

Reputation: 1032

Split 2D numpy array vertically into uneven subarrays

Suppose I have the following numpy array of shape (10, 5) where I want to split it into two subarrays: the first one contains the first 7 rows and the second one takes the remaining 3 rows. If I do this:

x = np.arange(50).reshape(10, 5)
x1, y1 = np.vsplit(x, 2)

It will split exactly half. How can I make it two subarrays (7,5) and (3,5)?

Upvotes: 0

Views: 220

Answers (2)

BENSALEM Mouhssen
BENSALEM Mouhssen

Reputation: 71

i think you shhould use fancy indexing, unlike slicing, fancy indexing always copies the data into a new array

n = 10; m = 5; i = 7
arr = np.arange(50).reshape(n, m)
arr7 = arr[np.ix_(range(i))]
arr3 = arr[np.ix_(range(i - n, 0, 1))]

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107357

Use np.split():

In [4]: np.split(x, [7])
Out[4]: 
[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],
        [30, 31, 32, 33, 34]]), array([[35, 36, 37, 38, 39],
        [40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49]])]

Upvotes: 2

Related Questions