Xav
Xav

Reputation: 51

How to extract slices and specific columns of a numpy array with one command?

I would like to extract both column slices and specific columns of a numpy array in one command.

For instance, for an array A:

import numpy as np
A = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])

I would like to select the columns from 0 to 2 together with the column 4. The solution A[:,(0,1,2,4)] works and is simple to implement in this example. For larger arrays, I am looking for a command of the type A[:,(0:3,4)] to select both slices and specific columns. The command A[:,(0:3,4)] does not work.

Is there an practical and elegant way of extracting both slices and specific columns with one command?

Many thanks in advance!

Upvotes: 0

Views: 1698

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 30991

As ombk suggested, you can use r_. It is a perfect tool to concatenate slice expressions.

In your case:

A[:, np.r_[0:3, 4]]

retrieves the intended part of your array.

Just the same way you can concatenate more slice expressions.

Upvotes: 2

Related Questions