-1

I have a date field called date1 and a weekday field called weekday in a dataframe called df. I am trying to create another field that if the weekday is a certain value, add a year,otherwise add a day. It comes up with an error:

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

So I added .any() and it runs but adds 365 days to all values.

if df['weekday'].any() < 6:
    df['date1'] = df['date'] + timedelta(365)
elif df['weekday'].any() == 6:
    df['date1'] = df['date'] + timedelta(1)
else:
    df['date1'] = datetime.today()

I am learning python and searched extensively on the Q&As here so would appreciate guidance. Thanks

deadshot
  • 8,881
  • 4
  • 20
  • 39

1 Answers1

3

This errors comes when you compare series with one element. Try this way-

for i, value in enumerate(df['weekday']):
    if value < 6:
        df['date1'][i] = df['date'][i] + timedelta(365)
    elif value == 6:
        df['date1'][i] = df['date'][i] + timedelta(1)
    else:
        df['date1'][i] = datetime.today()

Hope this will help you.

Kriti Pawar
  • 832
  • 7
  • 15
  • Works well, thanks. I get a warning message:"/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy This is separate from the ipykernel package so we can avoid doing imports until" – Jay Chilled May 21 '20 at 11:16