1

I have a Pandas dataframe with a DateTimeIndex and an empty column called WEEKEND.

I want to set the value of that column to 'YES' if the datetime in the index is on a weekend, so that the resulting dataframe is like this:

TIME                    WEEKEND
2019-01-01 00:00:00     NO
2019-01-02 06:00:00     NO
2019-01-03 21:00:00     NO
2019-01-04 18:00:00     NO
2019-01-05 03:00:00     YES
2019-01-06 07:00:00     YES
2019-01-07 10:00:00     NO
2019-01-08 08:00:00     NO

I know I can do this:

df.loc[df.index.dayofweek == 5, 'WEEKEND'] = "YES" # Saturday
df.loc[df.index.dayofweek == 6, 'WEEKEND'] = "YES" # Sunday

But I'd like to do it in one statement, using the IN keyword possibly.

I tried this, but I get an error:

df.loc[df.index.dayofweek in [5,6], 'WEEKEND'] = "YES"

What's the best way to achieve this?

Thank you

Vincent L
  • 699
  • 2
  • 11
  • 25
  • 2
    have a look at [isin](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html), like `df.index.dayofweek.isin([5,6])` – Ben.T Jul 16 '19 at 15:46
  • 1
    Possible duplicate of [How to implement 'in' and 'not in' for Pandas dataframe](https://stackoverflow.com/questions/19960077/how-to-implement-in-and-not-in-for-pandas-dataframe) – Ben.T Jul 16 '19 at 15:48

1 Answers1

1

You can apply or in .loc

df.loc[(df.index.dayofweek == 5) | (df.index.dayofweek == 6), 'WEEKEND'] = "YES"

second solution using .isin

df.loc[df.index.dayofweek.isin([5,6]) , 'WEEKEND'] = "YES"
tawab_shakeel
  • 3,701
  • 10
  • 26
  • 1
    The second answer is exactly what I wanted. I need to wait 7 minutes to accept this answer, but I will :) Thanks! – Vincent L Jul 16 '19 at 15:50