0

I have a data frame df with around 200 columns. I want to drop the columns with an index position from 50 to 90 and 120 to 170 with its name rather than its index position. How to do that.

I cannot use:

df.drop('column name', axis=1)

directly because there are so many columns to drop and I cannot really type each of its column names as in the above cases.

I am interested in knowing how to select the columns from particular column name column50 to another column name column90 and column120 to column170 rather than with the int

1

4 Answers 4

6

You can use np.r_ to do this:

import numpy
idx = np.r_[50:90, 120:170]

df.drop(df.columns[idx], axis=1, inplace=True)

From the np.r_ docs:

Translates slice objects to concatenation along the first axis.

In your case, it concatenates non-contiguous slices of arrays which you can use in df.drop command.

Sign up to request clarification or add additional context in comments.

Comments

4
df.drop(df.columns.to_series()["column_name_1":"column_name_2"], axis=1)

By converting to a series you can actually use a range to drop. You'd just need to know the column names.

2 Comments

Is it possible to select the columns from column_name_4 to column_name_6 along with column_name_1: column_name_2
Possibly, but I'm not sure about the syntax.
4

For non-contiguous slice objectss, always prefer to use np.r_.

The main goal for np.r_ is:

Translates slice objects to concatenation along the first axis.

Given that you have now concatenated, non-contiguous slice blocks, it gets easy to perform operations. You can use drop, loc, iloc or whatever logic you want (not much gain here beyond readability).

For example,

df = df.iloc[:, np.r_[50:90, 120:170]]

or, as suggested by @anky

df[df.columns ^ df.columns[np.r_[50:90,120:170]]]

Comments

2

You can create a list of columns like this:

idx = list(range(50,90)) + list(range(120,170))

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

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.