Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: An efficient way to merge multiple slices [duplicate]

I have a numpy array

test_array = np.arange(100).reshape((4,25))

and I want to merge the following cols to form a new array

1:3, 2:4, 3:15, 2:24, 6:8, 12:13

I know this code will work

np.hstack((test_array[:,1:3],test_array[:,2:4],test_array[:,3:15],test_array[:,2:24],test_array[:,6:8],test_array[:,12:13]))

But if there is any better way to avoid copying so many 'test_array', something like:

np.hstack((test_array[:,[1:3 2:4 3:15 2:24 6:8 12:13]]))
like image 410
FF0605 Avatar asked Oct 09 '17 07:10

FF0605


1 Answers

You can use np.r_ to create the respective range of indices from your slices. It also accepts multiple slice at once.

In [25]: test_array[:, np.r_[1:3, 2:4, 3:15, 2:24, 6:8, 12:13]]
Out[25]: 
array([[ 1,  2,  2,  3,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,  2,
         3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
        20, 21, 22, 23,  6,  7, 12],
       [26, 27, 27, 28, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 27,
        28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
        45, 46, 47, 48, 31, 32, 37],
       [51, 52, 52, 53, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 52,
        53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
        70, 71, 72, 73, 56, 57, 62],
       [76, 77, 77, 78, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 77,
        78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
        95, 96, 97, 98, 81, 82, 87]])

Note that as mentioned in comment using r_ is nicer to read and write but does't avoid copying data. And that's because Advanced Indexing always returns a copy, unlike the regular indexing that returns views from array.

like image 90
Mazdak Avatar answered Sep 24 '22 13:09

Mazdak