Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop multiple columns that end with certain string in Pandas

Tags:

python

pandas

I have a dataframe with a lot of columns using the suffix '_o'. Is there a way to drop all the columns that has '_o' in the end of its label?

In this post I've seen a way to drop the columns that start with something using the filter function. But how to drop the ones that end with something?

like image 740
aabujamra Avatar asked Mar 01 '18 23:03

aabujamra


People also ask

How do I drop multiple columns in pandas?

We can use Pandas drop() function to drop multiple columns from a dataframe. Pandas drop() is versatile and it can be used to drop rows of a dataframe as well. To use Pandas drop() function to drop columns, we provide the multiple columns that need to be dropped as a list.

How do you drop all columns except last one 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.

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. On below example df.


1 Answers

Pandonic

df = df.loc[:, ~df.columns.str.endswith('_o')]

df = df[df.columns[~df.columns.str.endswith('_o')]]

List comprehensions

df = df[[x for x in df if not x.endswith('_o')]]

df = df.drop([x for x in df if x.endswith('_o')], 1)
like image 125
jpp Avatar answered Oct 09 '22 00:10

jpp