Removing single and range of columns in pandas

Viewed 1537

What is the fastest way to drop columns[3] and columns[9:15]? (I'm only able to remove the columns in 2 steps using the df.drop method)

    1  2  3  4  5  6 ..  n
A   x  x  x  x  x  x ..  x
B   x  x  x  x  x  x ..  x
C   x  x  x  x  x  x ..  x 
3 Answers

You can, in fact, use pd.DataFrame.drop in one step. You can use np.r_ to combine multiple indices and ranges. Here's a demo:

df = pd.DataFrame(np.random.random((3, 20)))

print(df.columns)  # RangeIndex(start=0, stop=20, step=1)

res = df.drop(np.r_[3, 9:15], 1)

print(res.columns)

# Int64Index([0, 1, 2, 4, 5, 6, 7, 8, 15, 16, 17, 18, 19], dtype='int64')

Using simple loc and isin

cols = df.columns.tolist()
to_remove = cols[9:15] + [cols[3]]

df.loc[:, ~df.columns.isin(to_remove)]

but np.r_ is so nice I'd go with it ;)

Use as below:

>>> df
   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

>>> df.drop(['B', 'C'], axis=1)
   A   D
0  0   3
1  4   7
2  8  11
Related