Home > Software engineering >  iloc for cutting data for a spare set of columns by index
iloc for cutting data for a spare set of columns by index

Time:12-15

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?

CodePudding user response:

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

CodePudding user response:

Drop the column at index 1:

df_cut = df.drop(df.columns[1], axis=1)

Or use range:

df_cut = df.iloc[:,[0] list(range(2,5))]

CodePudding user response:

Another way:

df_cut = df[ [col for col_index, col in enumerate(df) if col_index != 1]]
  • Related