Python: How To Find The Nth Weekday Of The Year?
I have seen a lot of similar posts on 'nth weekday of the month', but my question pertains to 'nth weekday of the year'. Background: I have a table that has daily sales data. The
Solution 1:
The pandas package has some good time/date functions.
For example
import pandas as pd
s = pd.date_range('2020-01-01', '2020-12-31', freq='D').to_series()
print(s.dt.dayofweek)
gives you the weekdays as integers.
2020-01-01 22020-01-02 32020-01-03 42020-01-04 52020-01-05 62020-01-06 02020-01-07 12020-01-08 22020-01-09 32020-01-10 4
(Monday=0)
Then you can do
mondays = s.dt.dayofweek.eq(0)
If you want to find the first Monday of the year use.
print(mondays.idxmax())
Timestamp('2020-01-0600:00:00', freq='D')
Or the 5th Monday:
n = 4
print(s[mondays].iloc[n])
Timestamp('2020-02-03 00:00:00')
If your sales dataframe is df
then to compare sales on the first 5 Mondays of two different years you could do something like this:
mondays = df['Date'].dt.dayofweek.eq(0)
mondays_in_y1 = (df['Year'] == 2019) & mondays
mondays_in_y2 = (df['Year'] == 2020) & mondays
pd.DataFrame({
2019: df.loc[mondays_in_y1, 'Sales'].values[:5],
2020: df.loc[mondays_in_y2, 'Sales'].values[:5]
})
Solution 2:
IIUC you can play from
import pandas as pd
import numpy as np
df = pd.DataFrame({"date":pd.date_range(start="2020-01-01",
end="2020-12-31")})
# weekday number Monday is 0
df["dow"] = df["date"].dt.weekday
# is weekday as int
df["is_weekday"] = (df["dow"]<5).astype(int)
df["n"] = df["is_weekday"].cumsum()
# remove weekends
df["n"] = np.where(df["n"]==df["n"].shift(), np.nan, df["n"])
df[df["n"]==100]["date"]
Edit In two lines only
df["n"] = (df["date"].dt.weekday<5).astype(int).cumsum()
df["n"] = np.where(df["n"]==df["n"].shift(), np.nan, df["n"])
Solution 3:
You can try using dt.week
. It returns a series, but you can simply define a new column with these values.
For example:
import pandas as pd
rng = pd.date_range('2015-02-24', periods=5, freq='D')
df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))})
Output:
DateVal02015-02-24 -0.97727812015-02-25 0.95008822015-02-26 -0.15135732015-02-27 -0.10321942015-02-28 0.410599
The you should input df['Week_Number'] = df['Date'].dt.week
, so you will make a new column with the week number:
DateValWeek_Number02015-02-24 -0.977278912015-02-25 0.950088922015-02-26 -0.151357932015-02-27 -0.103219942015-02-28 0.4105999
Hope it helps. It's my first contribution.
Post a Comment for "Python: How To Find The Nth Weekday Of The Year?"