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.
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.
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.
To select all columns except one column in Pandas DataFrame, we can use df. loc[:, df. columns != <column name>].
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With