import pandas as pd
Pandas offers you a functionality to read the day of the week out of a datetime column: dt.weekday
. However these are values ranging from 0..6. Is there a better way to convert them to human-readable days rather than using our real-world knowledge? (yes, there is!)
generate the weekday names in a given locale
We can use the .dt.day_name()
function to generate named days. This function alone gets us only to discover that 2018-01-01 was a Monday. But we can do the following:
- Generate 7 consecutive dates with
pd.date_range()
- For each of them, read out its
.dt.weekday
- For each of them, read out its
.dt.day_name()
- Ignore/drop the first column and use the dataframe as a mapping between the integer denoting a day and its human-readable form.
Bonus: we can generate named days in a given locale. So for example to obtain a mapping between integers, day names in English, day names in German:
= pd.DataFrame(pd.date_range(start='2018-01-01', freq='D', periods=7), columns=['date'])
s 'weekday'] = s['date'].dt.weekday
s['weekday_en'] = s['date'].dt.day_name()
s['weekday_de'] = s['date'].dt.day_name(locale='de')
s[ s
date | weekday | weekday_en | weekday_de | |
---|---|---|---|---|
0 | 2018-01-01 | 0 | Monday | Montag |
1 | 2018-01-02 | 1 | Tuesday | Dienstag |
2 | 2018-01-03 | 2 | Wednesday | Mittwoch |
3 | 2018-01-04 | 3 | Thursday | Donnerstag |
4 | 2018-01-05 | 4 | Friday | Freitag |
5 | 2018-01-06 | 5 | Saturday | Samstag |
6 | 2018-01-07 | 6 | Sunday | Sonntag |
We can add variations of weekday names, such as:
'weekday_short'] = s['weekday_en'].apply(lambda x: x[0:3]).str.upper() s[
We can also create a dictionary:
= s[['weekday', 'weekday_short']].set_index('weekday_short')['weekday'].to_dict()
weekday_dict weekday_dict
{'MON': 0, 'TUE': 1, 'WED': 2, 'THU': 3, 'FRI': 4, 'SAT': 5, 'SUN': 6}