0

In python 3. with the library pandas, When using the fallowing code

    def check_question(df):
       mylambda = lambda x: x if x==x else x
       return df.apply(mylambda)

    print(check_question(df))

The console gave the fallowing ValueError:

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

After several tries the fallowing code fixed it:

   def check_question(df):
       mylambda = lambda x: x if [x==x] else x
       return df.apply(mylambda)

    print(check_question(df))

I known, it is something to do with the pandas library: Stackoverflow: The truth value of a Series is ambiguous

I realize that when encapsulation between [], the expression x==x value changes from an ambiguous-thuth-value to a truth-value. I have a vague idea of what it means, but if someone can enlight me more about it, it will greatly appreciated.

Alex Ricciardi
  • 181
  • 1
  • 9
  • What are you really trying to do? Is there a reason you don't use `.apply(lambda x: x)` directly? – gosuto Apr 25 '20 at 19:16
  • The expression x == x outputs True, if x = x. I could wrote x > 2 if I wanted to, it will output True if x = 3, but with pandas, it will generate a ValueError with the code df.apply(lambda x: x if x>2 else x), (if x>2 is not encapsulated with []). It was the point that I was trying to make. The Boolean output of the expression is what I am interested to. Related to the question, the return output of the lambda function is irrelevant. – Alex Ricciardi Apr 26 '20 at 02:15

1 Answers1

0

Your second example is not causing a ValueError because you are checking the truth value of a Python list (in this case [x == x]), which is defined. In contrast, the truth value of a Series is not defined (as you have mentioned).

See also https://docs.python.org/3/library/stdtypes.html#truth-value-testing

Ohley
  • 121
  • 1
  • 6