Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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.

like image 547
Sid Avatar asked Aug 30 '18 20:08

Sid


People also ask

How do I drop all columns except one in a DataFrame?

You can also acheive selecting all columns except one column by deleting the unwanted column using drop() method. Note that drop() is also used to drop rows from pandas DataFrame. In order to remove columns use axis=1 or columns param.

How do I drop the last 5 columns in pandas?

You can also use DataFrame. drop() method to delete the last n columns. Use axis=1 to specify the columns and inplace=True to apply the change on the existing DataFrame.

How do you select all columns first except in python?

To select all columns except one column in Pandas DataFrame, we can use df. loc[:, df. columns != <column name>].


1 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.)

like image 177
DSM Avatar answered Nov 15 '22 07:11

DSM