Selecting multiple columns, both consecutive and non-consecutive, in a Pandas dataframe

Issue

I am trying to run the following:

X = d.iloc[:, [13, 30, 35:45]].values

It fails at the range 35:45.

PS: There is this question with many useful answers, but they don’t address the issue of getting both consecutive and non-consecutive columns.

Solution

Use np.r_:

import numpy as np
X = d.iloc[:, np.r_[13, 30, 35:45]].to_numpy()

Intermediate output of np.r_[13, 30, 35:45]:

array([13, 30, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44])

Answered By – mozway

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published