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

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


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]: dfOut[323]: Empty DataFrameColumns: [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 DataFrameColumns: [A, B]Index: []


df.drop(df.columns[list(df.columns).index("B")+1:],inplace=True)