Как найти день недели в pandas

  • Редакция Кодкампа

17 авг. 2022 г.
читать 2 мин


Вы можете использовать следующие методы, чтобы найти день недели в pandas:

Метод 1: найти день недели как целое число

df['date_column']. dt.weekday

Способ 2: найти день недели в виде имени строки

df['date_column']. dt.day_name ()

В следующих примерах показано, как использовать каждый метод на практике со следующими пандами DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'date ': pd.date_range (start='1/5/2022', freq='D', periods= 10 ),
 'sales': [6, 8, 9, 5, 4, 8, 8, 3, 5, 9]})

#view DataFrame
print(df)

 date sales
0 2022-01-05 6
1 2022-01-06 8
2 2022-01-07 9
3 2022-01-08 5
4 2022-01-09 4
5 2022-01-10 8
6 2022-01-11 8
7 2022-01-12 3
8 2022-01-13 5
9 2022-01-14 9

Пример 1: найти день недели как целое число

В следующем коде показано, как добавить новый столбец в DataFrame, который показывает день недели в столбце даты в виде целого числа:

#add new column that displays day of week as integer
df['day_of_week'] = df['date']. dt.weekday

#view updated DataFrame
print(df)

 date sales day_of_week
0 2022-01-05 6 2
1 2022-01-06 8 3
2 2022-01-07 9 4
3 2022-01-08 5 5
4 2022-01-09 4 6
5 2022-01-10 8 0
6 2022-01-11 8 1
7 2022-01-12 3 2
8 2022-01-13 5 3
9 2022-01-14 9 4

В новом столбце day_of_week отображается день недели, где:

  • 0 : понедельник
  • 1 : вторник
  • 2 : среда
  • 3 : Четверг
  • 4 : пятница
  • 5 : суббота
  • 6 : воскресенье

Пример 2: найти день недели как строку имени

В следующем коде показано, как добавить новый столбец в DataFrame, который показывает день недели в столбце даты в виде целого числа:

#add new column that displays day of week as string name
df['day_of_week'] = df['date']. dt.day_name ()

#view updated DataFrame
print(df)

 date sales day_of_week
0 2022-01-05 6 Wednesday
1 2022-01-06 8 Thursday
2 2022-01-07 9 Friday
3 2022-01-08 5 Saturday
4 2022-01-09 4 Sunday
5 2022-01-10 8 Monday
6 2022-01-11 8 Tuesday
7 2022-01-12 3 Wednesday
8 2022-01-13 5 Thursday
9 2022-01-14 9 Friday

Новый столбец day_of_week отображает день недели в виде строкового имени.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:

Как сгруппировать по неделям в Pandas DataFrame
Как сгруппировать по месяцам в Pandas DataFrame

Use the new dt.dayofweek property:

In [2]:

df['weekday'] = df['Timestamp'].dt.dayofweek
df
Out[2]:
            Timestamp  Value  weekday
0 2012-06-01 00:00:00    100        4
1 2012-06-01 00:15:00    150        4
2 2012-06-01 00:30:00    120        4
3 2012-06-01 01:00:00    220        4
4 2012-06-01 01:15:00     80        4

In the situation where the Timestamp is your index you need to reset the index and then call the dt.dayofweek property:

In [14]:

df = df.reset_index()
df['weekday'] = df['Timestamp'].dt.dayofweek
df
Out[14]:
            Timestamp  Value  weekday
0 2012-06-01 00:00:00    100        4
1 2012-06-01 00:15:00    150        4
2 2012-06-01 00:30:00    120        4
3 2012-06-01 01:00:00    220        4
4 2012-06-01 01:15:00     80        4

Strangely if you try to create a series from the index in order to not reset the index you get NaN values as does using the result of reset_index to call the dt.dayofweek property without assigning the result of reset_index back to the original df:

In [16]:

df['weekday'] = pd.Series(df.index).dt.dayofweek
df
Out[16]:
                     Value  weekday
Timestamp                          
2012-06-01 00:00:00    100      NaN
2012-06-01 00:15:00    150      NaN
2012-06-01 00:30:00    120      NaN
2012-06-01 01:00:00    220      NaN
2012-06-01 01:15:00     80      NaN
In [17]:

df['weekday'] = df.reset_index()['Timestamp'].dt.dayofweek
df
Out[17]:
                     Value  weekday
Timestamp                          
2012-06-01 00:00:00    100      NaN
2012-06-01 00:15:00    150      NaN
2012-06-01 00:30:00    120      NaN
2012-06-01 01:00:00    220      NaN
2012-06-01 01:15:00     80      NaN

EDIT

As pointed out to me by user @joris you can just access the weekday attribute of the index so the following will work and is more compact:

df['Weekday'] = df.index.weekday

Last updated on 
Nov 11, 2021

In this quick tutorial, we’ll cover how we convert datetime to day of week or day name in Pandas.

There are two methods which can get day name of day of the week in Pandas:

(1) Get the name of the day from the week

df['date'].dt.day_name()

result:

0    Wednesday
1     Thursday

(2) Get the number of the day from the week

df['date'].dt.day_of_week

result:

0    2
1    3

Lets see a simple example which shows both ways.

Step 1: Create sample DataFrame with date

To start let’s create a basic DataFrame with date column:

import pandas as pd

data = {'productivity': [80, 20, 60, 30, 50, 55, 95],
        'salary': [3500, 1500, 2000, 1000, 2000, 1500, 4000],
        'age': [25, 30, 40, 35, 20, 40, 22],
        'duedate': ["2020-10-14", "2020-10-15","2020-10-15", "2020-10-17","2020-10-14","2020-10-14","2020-10-18"],
        'person': ['Tim', 'Jim', 'Kim', 'Bim', 'Dim', 'Sim', 'Lim']
       }
df = pd.DataFrame(data)
df

result:

productivity salary age duedate person
80 3500 25 2020-10-14 Tim
20 1500 30 2020-10-15 Jim
60 2000 40 2020-10-15 Kim
30 1000 35 2020-10-17 Bim
50 2000 20 2020-10-14 Dim

If the date column is stored as a string we need to convert it to datetime by:

df['date'] = pd.to_datetime(df['duedate'])

You can learn more about datetime conversion in this article: How to Fix Pandas to_datetime: Wrong Date and Errors.

Step 2: Extract Day of week from DateTime in Pandas

To return day names from datetime in Pandas you can use method: day_name:

df['date'].dt.day_name()

Tde result is days of week for each date:

0    Wednesday
1     Thursday
2     Thursday
3     Saturday
4    Wednesday

Default language is english. It will return different languages depending on your locale.

Step 3: Extract Day number of week from DateTime in Pandas

If you need to get the day number of the week you can use the following:

  • day_of_week
  • dayofweek — alias
  • weekday — alias

This method counts days starting from Monday — which is presented by 0.

So for our DataFrame above we will have:

df['date'].dt.day_of_week

day numbers of the week is the output:

0    2
1    3
2    3
3    5
4    2

The final DataFrame will look like:

duedate person date day_name day_number
2020-10-14 Tim 2020-10-14 Wednesday 2
2020-10-15 Jim 2020-10-15 Thursday 3
2020-10-15 Kim 2020-10-15 Thursday 3
2020-10-17 Bim 2020-10-17 Saturday 5
2020-10-14 Dim 2020-10-14 Wednesday 2

Step 4: Get day name and number of week

If you need to get both of them and use it at the same time. For example to plot bar chart with the natural order of the days — Starting from Monday, Tuesday etc

df[['day_number', 'salary', 'day_name']].groupby(['day_number', 'day_name']).mean().sort_index().plot(kind='bar', legend=None)

For more information and detailed example you can check this article: Dates and Bar Plots (per weekday) in Pandas

Resources

  • Notebook
  • pandas.Series.dt.day_name
  • pandas.Series.dt.day_of_week

In this short tutorial we’ll show how to use Python to easily convert a Pandas DataFrame datetime column and get instead the name of the weekday.

Create an example DataFrame

Let’s assume the following DataFrame:

import pandas as pd

#Define Data
office = ['Denver','Paris', 'Denver', 'London' ]
full_date = ['1-15-2022 13:45:00', '4-8-2022 08:45:00', '2-23-2022 12:45:00', '4-7-2022 13:46:00']
salary = [143, 153, 128, 149]
hiring_dict  = dict( office=office,hire_date=full_date,salary = salary)

# Create DataFrame
hiring_df = pd.DataFrame(data=hiring_dict)

Let’s look at the Data types of the DataFrame:

hiring_df.dtypes

Here’s the result we’ll get. It looks like we should first cast the hire_date column to datetime64 first.

office       object
hire_date    object
salary        int64
dtype: object

Convert datetime to day of week

If we’ll try to convert the hire_date column to day of the week we’ll receive an error.

hiring_df['hire_date'].dt.weekday

Pandas will throw the following message:

AttributeError: Can only use .dt accessor with datetimelike values

As mentioned above, before proceeding we first need to ensure our column data type is datetime. We can then use the dt accessor to find date values. Initially we’ll find the value of the day of the week of each observation in our data:

hiring_df['hire_weekday'] = 
pd.to_datetime(hiring_df['hire_date']).dt.weekday

Alternatively, we can use the following:



hiring_df['hire_weekday'] =  pd.to_datetime(hiring_df['hire_date']).dt.day_of_week

One more option is to use the astype method:


hiring_df['hire_weekday']= 
(hiring_df['hire_date']).astype('datetime64').dt.day_of_week

All the above will render the weekday number as shown below:

hiring_df.head()
office hire_date salary hire_weekday
0 Denver 1-15-2022 13:45:00 143 5
1 Paris 4-8-2022 08:45:00 153 4
2 Denver 2-23-2022 12:45:00 128 2
3 London 4-7-2022 13:46:00 149 3

Find the day of week name

In a similar fashion we can use the dt.day_name() function to retrieve the name of the week day.

hiring_df['hire_day_name'] = 
pd.to_datetime(hiring_df['hire_date']).dt.day_name()

Create a column with month names

As we have seen above,we ca use the dt accessor in order to extract several date/time values. In a similar fashion, we’ll now go ahead and extract the month name into a new DataFrame column:

hiring_df['hire_month'] =  pd.to_datetime(hiring_df['hire_date']).dt.month_name()

And here are our complete DataFrame values:

office hire_date salary hire_weekday hire_day_name hire_month
0 Denver 1-15-2022 13:45:00 143 5 Saturday January
1 Paris 4-8-2022 08:45:00 153 4 Friday April
2 Denver 2-23-2022 12:45:00 128 2 Wednesday February
3 London 4-7-2022 13:46:00 149 3 Thursday April

Weekday_name is the inbuilt method for finding the day of the week in pandas python. Also dayofweek function in pandas is used for getting the day of the week in numbers. Lets see how to

  • Get the Day of the week from date in English in pandas
  • Get the day of the week in number (starting from Monday , Monday = 0 and Sunday =6)

Let’s see an example of each

First lets create the dataframe

import pandas as pd
import numpy as np
import datetime

date1 = pd.Series(pd.date_range('2012-1-1 12:00:00', periods=7, freq='M'))
df = pd.DataFrame(dict(date_given=date1))
print(df)

so the resultant dataframe will be

Get day of the week in Pandas Python 1

Get the Day of the week in English in pandas

Weekday_name function Gets the day of the week in English Starting from Monday till sunday.  Which is shown in below code

df['day_of_week'] = df['date_given'].dt.weekday_name
print(df)

so the resultant dataframe will be

Get day of the week in Pandas Python 2

Get the Day of the week in Numbers – pandas

dayofweek function Gets the day of the week in numbers  Starting from Monday (Monday =0, Tuesday=1, Wednesday=2,Thursday =3,  Friday=4 ,  Saturday =5, Sunday =6)

df['day_of_week_in_number'] = df['date_given'].dt.dayofweek
print(df)

so the resultant dataframe will be

Get day of the week in Pandas Python 3

Get day of the week in Pandas Python                                                                                                          Get day of the week in Pandas Python

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти сумму одного столбца
  • Как приготовить как найти машину
  • Как найти потенциал в точке на схеме
  • Как на сайте налоговой найти выписку егрюл
  • Как найти артикул вещи на вайлдберриз

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии