Drop all columns before a particular column (by name) in pandas?

Viewed 7244

I found a bunch of answers about how to drop columns using index numbers.

I am stumped about how to drop all columns after a particular column by name.

df = pd.DataFrame(columns=['A','B','C','D'])
df.drop(['B':],inplace=True)

I expect the new df to have only A B columns.

4 Answers

Dropping all columns after is the same as keeping all columns up to and including. So:

In [321]: df = pd.DataFrame(columns=['A','B','C','D'])

In [322]: df = df.loc[:, :'B']

In [323]: df
Out[323]: 
Empty DataFrame
Columns: [A, B]
Index: []

(Using inplace is typically not worth it.)

get_loc and iloc

Dropping some is the same as selecting the others.

df.iloc[:, :df.columns.get_loc('B') + 1]

Empty DataFrame
Columns: [A, B]
Index: []
df.drop(df.columns[list(df.columns).index("B")+1:],inplace=True)

df = df[df.columns[:list(df.columns).index('B')+1]]

should work.

Related