2

This question touches upon the problem that I am facing. However, instead of excluding columns based on an exact string match, I want to exclude columns if a particular substring matches.

For example, in the image below, I would like to filter out columns A and C because they contain the substring 'is'

How would I go on about doing this? I replaced df.loc[:, ~(df == 'Salty').any()] from @cs95's answer to df.loc[:, ~(re.findall('/\w+(?:is)\w+/', df)).any()] but this gives me a

TypeError: expected string or bytes-like object 

Any help would be appreciated!

Input

|---------------------|------------------|----------------|----------| | | A | B | C | |---------------------|------------------|----------------|----------| | Value | Red | Green |Blue | |---------------------|------------------|----------------|----------| | 12 | HotisGood | Warm |isGood | |---------------------|------------------|----------------|----------| 

Output

|---------------------|--------------| | | B | |---------------------|--------------| | Value | Green | |---------------------|--------------| | 12 | Warm | |---------------------|--------------| 

1 Answer 1

3

You can do:

cols = df.apply(lambda x: x.str.contains('is').any()) df.loc[:, ~cols] 

Output:

 B Value Green 12 Warm 
Sign up to request clarification or add additional context in comments.

5 Comments

Hi! I included the sample input table and output table - is the image not visible/corrupted? Should I re-upload it?
@Mega_Noob no, images are not encouraged, see a guide to ask good question.
Understood, thank you. I will update the question right away - jbtw the output is the exact opposite of what I want (which is to exclude the columns that are being shown now and keep everything else)
@Mega_Noob please see updated. As you also see, the text data helps me debug my code and reproduce your expected outcome easily.
Thanks a ton! I'll keep formatting in mind for the future

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.