1

Suppose I have a DataFrame in Pandas like

   c1   c2
0  'ab'  1
1  'ac'  0
2  'bd'  0
3  'fa'  1
4  'de'  0

and I want it to show all rows such that c1 doesn't contain 'a'. My desired output would be:

   c1   c2
2  'bd'  0
4  'de'  0

My first attempt was to use df.loc, like this:

df.loc['a' not in df['c1']]

For searching specific values, df.loc works fine, but for searching based on a False condition ('a' not in df['c1']) it doesn't.

I know I can do the reverse thing. I mean, i can return all rows which contain 'a' in column 'c1', through this code:

df.loc[df['c1'].str.contains('a')]

But I just can't figure out an elegant/concise way to do the other way around. How can I do that?

1 Answer 1

3

Use ~ to flip your Series of booleans:

df.loc[~df['c1'].str.contains('a')]
Sign up to request clarification or add additional context in comments.

1 Comment

Works also without the ".loc" to condense it even more: df[~df['c1'].str.contains('a')]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.