3

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 
1

3 Answers 3

4

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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 ;)

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.