Let's say I have a DataFrame that looks like this:
a b c d e f g 1 2 3 4 5 6 7 4 3 7 1 6 9 4 8 9 0 2 4 2 1
How would I go about deleting every column besides a
and b
?
This would result in:
a b 1 2 4 3 8 9
I would like a way to delete these using a simple line of code that says, delete all columns besides a
and b
, because let's say hypothetically I have 1000 columns of data.
Thank you.
Select All Except One Column Using drop() Method in pandas In order to remove columns use axis=1 or columns param. For example df. drop("Discount",axis=1) removes Discount column by kepping all other columns untouched. This gives you a DataFrame with all columns with out one unwanted column.
To select all columns except one column in Pandas DataFrame, we can use df. loc[:, df. columns != <column name>].
We can exclude one column from the pandas dataframe by using the loc function. This function removes the column based on the location. Parameters: dataframe: is the input dataframe.
In [48]: df.drop(df.columns.difference(['a','b']), 1, inplace=True) Out[48]: a b 0 1 2 1 4 3 2 8 9
or:
In [55]: df = df.loc[:, df.columns.intersection(['a','b'])] In [56]: df Out[56]: a b 0 1 2 1 4 3 2 8 9
PS please be aware that the most idiomatic Pandas way to do that was already proposed by @Wen:
df = df[['a','b']]
or
df = df.loc[:, ['a','b']]
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