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

Kevin Sun :

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?

Code Different :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16595&siteId=1