0

There is a DataFrame df:

a  b
1  True
2  True
3  False

How do you make a subset of column a where column b is True?

output:

a 
1 
2  
3
  • What does your code look like? What have you tried so far? Commented Jul 22, 2017 at 18:00
  • 7
    df[df.b].... seriously you could've googled this Commented Jul 22, 2017 at 18:01
  • if your column C is boolean you can do what @COLDSPEED recommend Commented Jul 22, 2017 at 18:02

2 Answers 2

4

Use loc with boolean indexing and instead mask use column b:

...if need Series add a:

s = df.loc[df.b, 'a']
print (s)
0    1
1    2
Name: a, dtype: int64

...if need DataFrame (one column) add a in list:

df1 = df.loc[df.b, ['a']]
print (df1)
   a
0  1
1  2

And for all columns need boolean indexing only:

df1 = df[df.b]
print (df1)
   a     b
0  1  True
1  2  True

Also is possible use query:

print (df.query('b')['a'])
0    1
1    2
Name: a, dtype: int64

print (df.query('b')[['a']])
   a
0  1
1  2

print (df.query('b'))
   a     b
0  1  True
1  2  True
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to get back the data frame, use:

df1 = pd.DataFrame(df[df['b'] == True]['a'])

If you want to get the output a, use:

df1 = df[df['b'] == True]['a']
print (df1)

Comments

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.