Search code examples
pythonpandasdata-analysis

iloc for cutting data for a spare set of columns by index


df = pd.DataFrame({'name':['jack', 'james', 'joe'], 'age':[30, 40, 50], 'height': [6.0, 5.9, 5.5], 'is_married':[1,0,1], 'is_parent':[0,1,1]})

I want to select only columns indices: 0, 2, 3, 4 (but not 1). The following works fine:

df_cut = df.iloc[:,[0,2,3,4]]

But instead of passing every specific column index, I am looking for a way that I can pass. I tried:

df_cut = df.iloc[:,[0,[2:4]]

But it doesn't work. What is the best solution?


Solution

  • You need np.r_ from numpy

    df_cut = df.iloc[:,np.r_[0,2:4+1]]
    df_cut
    Out[338]: 
        name  height  is_married  is_parent
    0   jack     6.0           1          0
    1  james     5.9           0          1
    2    joe     5.5           1          1