23

I have a dataframe with one column(dtype=bool) contains True/False values, I want to filter the records if bool column == False

Below script gives error, please help.

if mFile['CCK'].str.contains(['False']):
    print(mFile.loc[mFile['CCK'] == False])

Error in

if mFile['CCK'].str.contains(['False']
cs95
  • 379,657
  • 97
  • 704
  • 746
Learnings
  • 2,780
  • 9
  • 35
  • 55

3 Answers3

23

You don't need to convert the value to a string (str.contains) because it's already a boolean. In fact, since it's a boolean, if you want to keep only the true values, all you need is:

mFile[mFile["CCK"]]

Assuming mFile is a dataframe and CCK only contains True and False values

Edit: If you want false values use:

mFile[~mFile["CCK"]]
ConorSheehan1
  • 1,640
  • 1
  • 18
  • 30
14

To display only if a record is False, you'll need to invert your condition:

mFile[~mFile['CCK']])

MVCE:

Original:

In [1273]: df
Out[1273]: 
       A    B
0  False    8
1   True   98
2   True   97
3  False  106
4  False   50
5  False   80
6  False   80
7   True   72
8  False  117
9  False   29

Using boolean indexing:

In [1271]: df[~df.A].B
Out[1271]: 
0      8
3    106
4     50
5     80
6     80
8    117
9     29
Name: B, dtype: int64

You could also use pd.Series.mask:

In [1272]: df.B.mask(df.A).dropna()
Out[1272]: 
0      8.0
3    106.0
4     50.0
5     80.0
6     80.0
8    117.0
9     29.0
Name: B, dtype: float64

If your data has string entries, you'd need pd.Series.str.contains:

In [1278]: df[df.A.astype(str).str.contains('False')]
Out[1278]: 
       A    B
0  False    8
3  False  106
4  False   50
5  False   80
6  False   80
8  False  117
9  False   29

For your case, it'd be

mFile[mFile['CCK'].astype(str).str.contains('False') ]

To check if False-y values exist, just get the mask and call pd.Series.any():

mFile['CCK'].astype(str).str.contains('False').any()
cs95
  • 379,657
  • 97
  • 704
  • 746
  • display working fine, but how to apply if mFile['CCK'].contains(['False']) then only display as some data frame as true only – Learnings Aug 25 '17 at 11:48
  • @faithon Edited my answer. – cs95 Aug 25 '17 at 11:51
  • 1
    @faithon Can you please stick to one person instead of jockeying between answers? Also, more queries go into separate questions. If this worked fine, then you should mark an answer accepted. – cs95 Aug 25 '17 at 11:54
  • 1
    question isn't really clear... i think he just wants to check if at least one `False in mFile['CCK']`... – Jörn Hees Aug 25 '17 at 11:56
  • @faithon You might consider other methods as I've outlined in my answer. – cs95 Aug 25 '17 at 12:05
3

how about:

if False in mFile['CCK']:
    print(mFile[~mFile['CCK']])

you can use ~ as above or mFile['CCK'] == False, which might be a bit more readable to others...

Jörn Hees
  • 3,338
  • 22
  • 44