5

I have dataframe with >100 columns. I am trying to select the columns 0~32 and #83. It seems that 1 slice works fine with the code below.

df_new = df[df.columns[0:32]]

It does not work with 2 slices code below though. How do I fix the problem?

df_new = df[df.columns[0:32, 83]]

3 Answers 3

10

Use the np.r_ indexer in conjunction with iloc, like this:

df.iloc[:, np.r_[0:32, 83]]

np.r_[0:32, 83]

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 83])
Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately first/last like this doesn't work, df.iloc[:, np.r_[0, -3:]]. If anyone has a solution to that using np.r_ it would be a nice addition to this answer.
@DavidParks I'm surprised this isn't better supported but here you go: c = df.shape[1]; df.iloc[:, np.r_[0, nc-3:nc]]
@cs95 I think it will be good to add the comment in the answer.
After using this method (np.r_), when I extract a column of a dataframe it becomes a DataFrame (type is: pandas.core.frame.DataFrame) instead of a series. Why does this happen? Any way to make this a series?
3

np.r_ is an excellent answer. The other approach would be to construct it with list and range.

Consider this example:

import pandas as pd

df = pd.DataFrame([range(10)],range(10))
cols = list(range(0,5))+[8]              # 0,1,2,3,4,8
df.iloc[:,cols]

Comments

0

I am also interest in this problem. We can choose several separate lines or columns. But it seems slicing operation could be done only once on each axis. Like the following one.

new_df=df.iloc[[2,3,4],[3:4]]

Maybe we can slice first and then concatenate them together.

df1=df.iloc[[2:4],:]
df2=df.iloc[[8:10],:]
new_df=pd.concat([df1,df2],axis=0)

2 Comments

This is slicing rows, but op wants columns
I definitely considered selecting 2 slices and concatenating, but thought there must be an easier way which was shown in the first answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.