Search code examples
pythonpandasconditional-statements

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). in conditional in python


I tried to do

if (df1['Year']>5)&(df1['TotalMntProducts']>2000):
  print(1)
else:
  print(0)

this in order to make a new column by condition and got ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

what should I do?


Solution

  • Are these Pandas DataFrames?

    df1['new_column'] = df1.apply(lambda row: 1 if row.Year > 5 and row.TotalMntProducts > 2000 else 0, axis=1)
    

    Improved Edit... let's vectorize:

    df1['new_column'] = (df.Year.gt(5) & df.TotalMntProducts.gt(2000)).astype(int)