Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: select rows where two columns are different

Tags:

python

pandas

Suppose I have a dataframe as below

a  b  c  
1  1  45
0  2  74
2  2  54
1  4  44

Now I want the rows where column a and b are not same. So the expected outpu is

a  b  c 
0  2  74
1  4  44

How can I do this?

like image 861
user1670773 Avatar asked Feb 12 '18 16:02

user1670773


3 Answers

I am a fan of readability, use query:

df.query('a != b')

Output:

   a  b   c
1  0  2  74
3  1  4  44
like image 173
Scott Boston Avatar answered Oct 13 '22 09:10

Scott Boston


Try this:

df.loc[df['a'] != df['b']]
like image 23
jpp Avatar answered Oct 13 '22 10:10

jpp


By using nunique

df.loc[df[['a','b']].nunique(1)>1]
Out[335]: 
   a  b   c
1  0  2  74
3  1  4  44
like image 42
BENY Avatar answered Oct 13 '22 11:10

BENY