Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop column based on a string condition

How can I delete a dataframe column based on a certain string in its name?

Example:

           house1    house2    chair1  chair2
index
  1         foo       lee       sam      han
  2         fowler    smith     had      sid
  3         cle       meg       mag      mog

I want to drop the columns that contain 'chair' in the string. How can this be done in an efficient way? Thanks.

like image 233
Al_Iskander Avatar asked Jul 14 '16 20:07

Al_Iskander


People also ask

How do I drop a column in a DataFrame based on a condition?

During the data analysis operation on a dataframe, you may need to drop a column in Pandas. You can drop column in pandas dataframe using the df. drop(“column_name”, axis=1, inplace=True) statement.

How do you set a column value based on condition?

Method 1 : Using dataframe. With this method, we can access a group of rows or columns with a condition or a boolean array. If we can access it we can also manipulate the values, Yes! this is our first method by the dataframe. loc[] function in pandas we can access a column and change its values with a condition.

How do I drop a column in Pandas based on index?

Pandas Drop Multiple Columns By Index You can use df. columns[[index1, index2, indexn]] to identify the list of column names in that index position and pass that list to the drop method. Note that an index is 0 based. Use 0 to delete the first column and 1 to delete the second column and so on.


1 Answers

df.drop([col for col in df.columns if 'chair' in col],axis=1,inplace=True)
like image 114
mechanical_meat Avatar answered Oct 04 '22 22:10

mechanical_meat