0

Let's say I have the following dataframe:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(4,8), columns = list('abcdefgh'))

I would like to choose column c and columns e to h.

I know I could do something like:

df.iloc[:,[2,4,5,6,7]]

but for larger dataframes it becomes inconvenient. I'm wondering if there is anything that could be similar to this:

df.iloc[:,[2,4:]]

so a way of combining single columns with slices?

egil137
  • 25
  • 5

1 Answers1

0

Use numpy.r_:

print (df.iloc[:,np.r_[2,4:len(df.columns)]])
          c         e         f         g         h
0  0.111579  0.745122  0.149010  0.571919  0.342449
1  0.264858  0.310361  0.793848  0.312512  0.283363
2  0.862014  0.988839  0.294116  0.442045  0.439055
3  0.364002  0.492306  0.539654  0.003055  0.877452
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252