0

i want new column ['pred_n'] to be created based on certain condition, condition is as follows: if year is less than or equal to current year & month is less than current month, pred_n should be equal to yhatpct else it should be yhatpct_ft. trying following syntax:

if((dfyz['year_x'] < datetime.now().year) | ((dfyz['year_x'] == datetime.now().year) & (dfyz['mon'] < datetime.now().month))):
    dfyz['pred_n'] = dfyz['yhat']*dfyz['pct']
else:
    dfyz['pred_n'] = dfyz['yhat']*dfyz['pct_ft']

but output shows only if condition though in my data I have month and year from 2019 - 08 onwards and if i use

if ((dfyz['year_x'] < datetime.now().year) | ((dfyz['year_x'] == datetime.now().year) & (dfyz['mon'] < datetime.now().month))):
     dfyz['pred_n'] = dfyz['yhat']*dfyz['pct']
elif (((dfyz['year_x'] == datetime.now().year) & (dfyz['mon'] >= datetime.now().month)) | ((dfyz['year_x'] > datetime.now().year))):
       dfyz['pred_n'] = dfyz['yhat']*dfyz['pct_ft']

it gives output only for else condition

3
  • Use or instead of | and and instead of & in Python expressions. Also consider writing now = datetime.now() and replacing all those calls in the expressions. Together, these will make your logic much easier to read (and reason about)”. Commented Sep 16, 2021 at 1:38
  • with or, and it shows following error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Commented Sep 16, 2021 at 1:46
  • Decompose your conditions using variables (also helps to fix now() to a definite point in time for all your comparisons). Choose the variable names wisely so the expresisons are easier to read. And yes, Python logical opertors are and or not Commented Sep 16, 2021 at 1:51

1 Answer 1

2

You are currently using the bitwise operators | and &, rather than the logical operators orand and. Presumably you really want something like:

now = datetime.now()
if (dfyz['year_x'] < now.year or        
    dfyz['year_x'] == now.year and dfyz['mon'] < now.month
):
    ...

(Its not great practice to keep calling now several times ... each of your calls is potentially returning a different value for now)

Sign up to request clarification or add additional context in comments.

1 Comment

or, and it shows following error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). now = datetime.now() if ((dfyz['year_x'] < now.year) or ((dfyz['year_x'] == now.year) and (dfyz['mon'] < now.month))): dfyz['pred_n'] = dfyz['yhat']*dfyz['pct'] elif (((dfyz['year_x'] == now.year) and (dfyz['mon'] >= now.month)) or ((dfyz['year_x'] > now.year))): dfyz['pred_n'] = dfyz['yhat']*dfyz['pct_ft']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.