2

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]
mapperx
  • 197
  • 1
  • 2
  • 12

2 Answers2

2

You can use numpy:

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

np.r_ will concatenate the indexes for you.

TitoOrt
  • 1,265
  • 1
  • 11
  • 13
  • Been trying to figure this out for a while just couldn't get my head around it. This np.r_ solved it. – mapperx Jan 14 '22 at 13:40
2

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)
Rabinzel
  • 7,757
  • 3
  • 10
  • 30