Dervin Thunk
Dervin Thunk

Reputation: 20139

Display two columns with a condition in Pandas

Suppose I have a dataframe df such as

A  B  C
0  a  1
1  b  1
2  c  2

I would like to return B, and C when C==1, like so

B  C
a  1
b  1

I've got as far as df.B[df.C==1], which returns

B
a
b

which is right (countwise) but wrong in the slice. How do I get C?

Upvotes: 4

Views: 9220

Answers (1)

jezrael
jezrael

Reputation: 863166

You can use loc or query:

print df.loc[df.C==1, ['B','C']]
   B  C
0  a  1
1  b  1

print df[['B','C']].query('C == 1')
   B  C
0  a  1
1  b  1

Or if you need only column C:

print df.loc[df.C==1, 'C']

0    1
1    1
Name: C, dtype: int64

Upvotes: 5

Related Questions