Home > Software engineering >  Multiple selection of dataframe using multiple column slices
Multiple selection of dataframe using multiple column slices

Time:01-15

I have a dataframe that has 10 columns, I am trying select columns 1 to 3 (first to third) and columns 5 to 8 (fifth to eighth). Is it possible to select using the iloc selector so that it can take multiple slices. The sample below can slice first to third, I would like to add the columns 5 to 8 as well

df = pc_df.iloc[:,0:4]

CodePudding user response:

You can use numpy:

#import  numpy as np
df.iloc[:,np.r_[0:4, 5:9]]

np.r_ will concatenate the indexes for you.

CodePudding user response:

Didn't know about np.r_, so also thanks to Tito from me!

If you don't want to use extra lib, you could also use pd.concat

pd.concat([df.iloc[:,:4], df.iloc[:, 5:9]],1)
  •  Tags:  
  • Related