Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting one NumPy array into two arrays

Suppose I have a NumPy 2D array A:

>>> import numpy as np
>>> A=np.arange(30).reshape(3,10)
>>> A
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 need to get two arrays B and C with the following properties:

B = array([[ 0,  3,  4,  5,  6,  7,  8,  9],
           [10, 13, 14, 15, 16, 17, 18, 19],
           [20, 23, 24, 25, 26, 27, 28, 29]])

C = array([[ 1,  2],
           [11, 12],
           [21, 22]])

What is the easiest way to accomplish this?

Note that I have to get all sets of C (2 adjacent columns) and B (which is A without C). I tried different NumPy constructs like np.delete, np.hstack but nothing seem to work at the corner conditions like in the above example.

like image 622
pynewbie Avatar asked Oct 26 '14 09:10

pynewbie


1 Answers

One of the simplest ways is to use indexing to select the appropriate columns:

>>> A[:, [1, 2]] # choose all rows from columns 1-2 (gives C)
array([[ 1,  2],
       [11, 12],
       [21, 22]])

>>> A[:, np.r_[0, 3:10]] # choose all rows from columns 0, 3-9 (gives B)
array([[ 0,  3,  4,  5,  6,  7,  8,  9],
       [10, 13, 14, 15, 16, 17, 18, 19],
       [20, 23, 24, 25, 26, 27, 28, 29]])

Alternatively, you could try hsplit break up A and then concatenate bits back together. This feels less efficient than the indexing method above though:

>>> splits = np.hsplit(A, [1, 3]) 
>>> B = np.hstack((splits[0], splits[2]))
>>> C = splits[1]
like image 161
Alex Riley Avatar answered Sep 26 '22 02:09

Alex Riley