2

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

  • 1
    Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – AMC Sep 04 '20 at 00:32
  • @AMC while I agree `()`s around the clauses would work, many of these answers also address the fact the this complex set of conditions is unnecessary and go beyond just point out the precedence issues. It is not normal to comment and downvote all the answers for a dupe question. Flag or vote the question. – AChampion Sep 04 '20 at 01:00
  • @AChampion _while I agree ()s around the clauses would work, many of these answers also address the fact the this complex set of conditions is unnecessary and go beyond just point out the precedence issues._ Even if we ignore the duplicate issue, the question is still missing a MCVE, and part of the error output. – AMC Sep 04 '20 at 01:05
  • _It is not normal to comment and downvote all the answers for a dupe question._ What does _normal_ mean, and according to who? I shared a few posts in [the discussion with BEN_YO](https://chat.stackoverflow.com/rooms/220948/discussion-between-ben-yo-and-amc) which show that it isn't all *that* rare. – AMC Sep 04 '20 at 01:05

4 Answers4

0

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.

DYZ
  • 55,249
  • 10
  • 64
  • 93
0

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

df[(df['X'] & ~df['Z']) | (~df['X'] & df['Z'])]
Andy L.
  • 24,909
  • 4
  • 17
  • 29
0

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]
BENY
  • 317,841
  • 20
  • 164
  • 234
0

If X and Y contain only True and False, the below will give the answer (please check How do you get the logical xor of two variables in Python?):

df[df['X']!=df['Z']]
Sam S.
  • 627
  • 1
  • 7
  • 23