user12907213
user12907213

Reputation:

Filtering boolean values in pandas

I am trying to filter only columns with True values from this dataset:

Name Surname Age New_Joiner
Greta G.     56    False
Tim   H.     24    True
Rita  F.     46    False
Sara  S.     34    True
...

My expected output would be

Name Surname Age New_Joiner
Tim   H.     24    True
Sara  S.     34    True
...

I have tried to add this selection condition in a very small function (probably it does not make a lot of sense):

def filt(file):
    file[['New_Joiner']]
    return file

But when I call it

sel=filt(df)

I got not only True values but also False. I checked the type of New_Joiner column using dtype and it is boolean.

Upvotes: 1

Views: 112

Answers (3)

s3dev
s3dev

Reputation: 9731

Expanding on my comment now that I’ve tested. You can skip the function all together and use:

df[df['New_Joiner']]

This will only return the True values as it’s a boolean mask.

Upvotes: 1

Ricardo Rendich
Ricardo Rendich

Reputation: 651

You don't need two steps, just

sel = file[file['New_Joiner']]

Upvotes: 2

BENY
BENY

Reputation: 323396

Change your function to

def filt(file):
    file = file[file['New_Joiner']]
    return file

Upvotes: 2

Related Questions