Reputation: 739
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
Upvotes: 1
Views: 143
Reputation: 3739
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"
Upvotes: 1