Selecting rows in pandas dataframe

Viewed 81

I would need to select rows satisfying the following conditions:

  • if (X is True and Z is false) | ( X is false and Z is true) then assign to a new column True as value.

I tried with this:

df[(df[X']==True & df['Z']==False) | (df['X']==False & df['Z']==True)]

but I got the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I have tried using any() as follows

4 Answers

df['X']==True & df['Z']==False must be (df['X']==True) & (df['Z']==False) (and everything else, respectively). In Python, operator & has a higher precedence than ==. Your expression is interpreted as df['X']==(True & df['Z'])==False.

If all your values are boolean values as in you conditions, you may try this

df[(df['X'] & ~df['Z']) | (~df['X'] & df['Z'])]

Check with

df[((df['X']==True) & (df['Z']==False)) | ((df['X']==False) & (df['Z']==True))]

Also a little math here

df[df.X.astype(int).add(df.Z.astype(int)==1]

From Achampion

df[df.X!=df.Z]
Related