0

I'm trying this

import pandas as pd
df = pd.DataFrame(range(0, 10))
df[1] = df[0] % 2 == 0
df[2] = 1 if df[1] else 0

which gives me this error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_2233547/1119079756.py in ?()
      1 df = pd.DataFrame(range(0, 10))
      2 df[1] = df[0] % 2 == 0
----> 3 df[2] = 1 if df[1] else df[0]

~/.local/lib/python3.11/site-packages/pandas/core/generic.py in ?(self)
   1464     @final
   1465     def __nonzero__(self) -> NoReturn:
-> 1466         raise ValueError(
   1467             f"The truth value of a {type(self).__name__} is ambiguous. "
   1468             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1469         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
geckos
  • 5,687
  • 1
  • 41
  • 53
  • 1
    I'm not sure what you're expecting here. Remember that `True` equals 1 and `False` equals 0, so your `df[1]` column already has the data you want. At worst, you could do `df[2] = df[1].astype(int)`, but that seems silly. – Tim Roberts Aug 04 '23 at 18:15
  • 1
    The root of the problem is that the ternary operator (`x if y else z`) cannot be vectorized. It's a pure Python expression, not involving pandas, and Python needs to have the center value be a simple boolean scalar. – Tim Roberts Aug 04 '23 at 18:17
  • The 1 and 0 are just examples I had a calculation in the real case, thanks for the comments – geckos Aug 04 '23 at 21:13
  • Well, the answer to your question depends very strongly on your data. If you can't share what you're actually doing, we can't really help very much. – Tim Roberts Aug 05 '23 at 00:17
  • The question was marked as duplicated and the answer of the another question helped, no worries – geckos Aug 09 '23 at 00:31

0 Answers0