How do select certain column indexes (continuous and individual) in Pandas

Viewed 77

I come from an R background and am having trouble slicing certain sets of columns in pandas.

Let's say I am trying to get the columns with index 0, 3, 5 through 20, and 25th. I would think the way to access what I want is:

df.iloc[:, [0,3,5:20,25]]

but there is a syntax error with the : within the 5:20 line of code. Is there a way to generate a sequence of numbers from 5 through 20 without typing each number out?

2 Answers

You can use numpy.r_[...]:

df.iloc[:, np.r_[0,3,5:21,25]]

Notice that the slice is 5:21 since numpy uses Python's slicing convention (exclude the upperbound) while pandas includes both the lower and upperbound.

You could build the list first and then use .iloc[] with it.

my_list = [0, 3]
my_list.extend(range(5, 21))
my_list.extend([25])
df.iloc[my_list]
Related