mihasa
mihasa

Reputation: 1017

Python: Eliminating rows in Pandas DataFrame based on boolean condition

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?

Upvotes: 1

Views: 235

Answers (1)

TomAugspurger
TomAugspurger

Reputation: 28926

Use ~ to flip your Series of booleans:

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

Upvotes: 3

Related Questions