search
Search
Unlock 100+ guides
search toc
close
Outline
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Dropping columns whose label contains a substring in Pandas

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Consider the following DataFrame:

``` df = pd.DataFrame({"ABC":[3,4],"BCD":[5,6],"E":[7,8]})df ABC BCD E0 3 5 71 4 6 8 ```

# Solution

To drop columns whose label contains a specific substring in Pandas:

``` df.loc[:, ~df.columns.str.contains("BC")] E0 71 8 ```

# Explanation

We first extract the column labels of `df` using the `columns` property:

``` df.columns Index(['ABC', 'BCD', 'E'], dtype='object') ```

We then use the `str.contains(~)` method to get an array of booleans indicating which column labels contain the specified substring:

``` df.columns.str.contains("BC")   # returns a NumPy array array([ True, True, False]) ```

The other way of interpreting "dropping some columns" is "selecting other columns", so we reverse the boolean mask using `~`:

``` ~df.columns.str.contains("BC") array([False, False, True]) ```

This now tells us which columns to keep.

Finally, we use the `loc` property to select columns that correspond to `True` in our mask:

``` df.loc[:, ~df.columns.str.contains("BC")] E0 71 8 ```

Here, note the following:

• `:` before the comma indicates that we want to fetch all rows

• the boolean mask after the `:` indicates that we want to fetch the columns with corresponding entry `True`.

Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
3
thumb_down
1
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!