Selecting a range of columns in a dataframe

Advanced indexing doesn’t take a list of lists of slices. Instead, you can use numpy.r_. This function doesn’t take negative indices, but you can get round this by using np.ndarray.shape:

A = B[:, np.r_[1:6, 7:B.shape[1]-1]]

Remember to add 1 to the second part, since a: b does not include b, in the same way slice(a, b) does not include b. Also note that indexing begins at 0.

Here’s a demo:

import numpy as np

B = np.random.randint(0, 10, (3, 11))

print(B)

[[5 8 8 8 3 0 7 2 1 6 7]
 [4 3 8 7 3 7 5 6 0 5 7]
 [1 0 4 0 2 2 5 1 4 2 3]]

A = B[:,np.r_[1:6, 7:B.shape[1]-1]]

print(A)

[[8 8 8 3 0 2 1 6]
 [3 8 7 3 7 6 0 5]
 [0 4 0 2 2 1 4 2]]

Leave a Comment