0

I have a DataFrame like this:

    Customer Id     Date        Product
0   001             2020-07-20  tropical fruit
1   002             2020-04-30  whole milk
2   003             2020-09-18  pip fruit
3   004             2020-12-11  other vegetables
4   005             2020-01-02  whole milk
    ...

and I want to add a column to keep corresponding weekday.

How can I do this?

Moj Taba
  • 85
  • 6

2 Answers2

0

You can use dt.dayofweek and dt.day_name:

df['Date'] = pd.to_datetime(df['Date'])
df['weekday'] = df['Id'].dt.dayofweek
df['weekday name'] = pd.to_datetime(df['Date']).dt.day_name()

Output:

   Customer Id  Date     Product          weekday weekday name
0         1 2020-07-20  tropical fruit       0       Monday
1         2 2020-04-30     whole milk        3     Thursday
2         3 2020-09-18       pip fruit       4       Friday
3         4 2020-12-11     other vegetables  4       Friday
4         5 2020-01-02     whole milk        3     Thursday
0

With something like this :

df["WeekDay"] = df["Date"].to_series().apply(lambda date: date.day_name())

You can also add a datetime parsing in the lambda pd.to_datetime(date) if Date is a simple string object.

Ludwig
  • 328
  • 1
  • 6