Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all columns in DataFrame except certain ones?

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.

like image 341
sgerbhctim Avatar asked Aug 23 '17 17:08

sgerbhctim


People also ask

How delete all columns except one in pandas?

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.

How do I get all columns except last one?

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

How do I exclude one column from a DataFrame?

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.


1 Answers

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']] 
like image 97
MaxU - stop WAR against UA Avatar answered Sep 19 '22 18:09

MaxU - stop WAR against UA