Reputation: 479
I have a pandas dataframe that contains a date
column. I would like to add another column called day_of_week
to this df that tells the day of the week in German. Based on this answer, I understand that I can do this by using the Babel package.
>>> from datetime import date, datetime, time
>>> from babel.dates import format_date, format_datetime, format_time
>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en')
u'Apr 1, 2007'
>>> format_date(d, locale='de_DE')
u'01.04.2007'
However, when I try to apply this to a pandas dataframe column, I get an AssertionError:
:
df['day_of_week'] = format_date(df['date'], "E", locale='de_DE')
Does anyone have an idea how to fix this?
Upvotes: 0
Views: 638
Reputation: 120409
Use apply
:
df['day_of_week'] = df['date'].apply(format_date, format='E', locale='de_DE')
print(df)
# Output
date day_of_week
0 2022-01-28 Fr.
1 2022-01-29 Sa.
2 2022-01-30 So.
3 2022-01-31 Mo.
4 2022-02-01 Di.
5 2022-02-02 Mi.
6 2022-02-03 Do.
7 2022-02-04 Fr.
8 2022-02-05 Sa.
9 2022-02-06 So.
Setup:
df = pd.DataFrame({'date': pd.date_range('2022-1-28', '2022-2-6')})
print(df)
# Output
date day_of_week
0 2022-01-28 Fr.
1 2022-01-29 Sa.
2 2022-01-30 So.
3 2022-01-31 Mo.
4 2022-02-01 Di.
5 2022-02-02 Mi.
6 2022-02-03 Do.
7 2022-02-04 Fr.
8 2022-02-05 Sa.
9 2022-02-06 So.
As a suggestion with locales
:
import locale
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8') # Linux
locale.setlocale(locale.LC_TIME, 'German') # Windows
df['day_of_week'] = pd.to_datetime(df['date']).dt.strftime('%a.')
Upvotes: 1