Index two sets of columns in an array

I am trying to cut columns from an array and assign a new variable, for example.

array1 = array[:,[0,1,2,3,15,16,17,18,19,20]]

Is there a shortcut for something like this?

I tried this, but he made a mistake:

array1 = array[:,[0:3,15:20]]

It is probably very simple, but I can not find it anywhere.

+4
source share
3 answers

Use np.r_:

Translates slice objects into concatenation along the first axis.

import numpy as np
arr = np.arange(100).reshape(5, 20)
cols = np.r_[:3, 15:20]

print(arr[:, cols])
[[ 0  1  2 15 16 17 18 19]
 [20 21 22 35 36 37 38 39]
 [40 41 42 55 56 57 58 59]
 [60 61 62 75 76 77 78 79]
 [80 81 82 95 96 97 98 99]]

At the end of the day, it’s probably only a little less detailed than what you have now, but it may come in handy for more complex cases.

+4
source

For most simple cases like this, the best and easiest way is to use concatenation:

array1 = array[0:3] + array[15:20]

, NumPy s_, , . .

, (.. 5, 10, 5 ..), itertools.compress, ncoghlan this.

+3

you can use list(range(0, 4)) + list(range(15, 20))

0
source

Source: https://habr.com/ru/post/1680249/


All Articles