I would like to convert a column of a dataframe containing weekday integers into its corresponding weekday name. So 0 should become Monday, 1 Tuesday and so forth.
I have tried to convert the integers into a datetime format but it does not work. What is the best way to go about it?
data = {'weekday_number': [1, 2, 0, 3, 4, 5, 6, 3, 2, 5, 4, 5]}
df = pd.DataFrame(data)
df['weekday_name'] = pd.to_datetime(df['weekday_number']).dt.strftime('%A')
Use map
for that. First, create a dictionary for mapping days with their numbers
days = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}
then
df['weekday_name'] = df['weekday_number'].map(days)
You can use date
objects to do the conversion, by using your weekday number as a timedelta
from a date which is a Monday:
import pandas as pd
from datetime import date, timedelta
data = {'weekday_number': [1, 2, 0, 3, 4, 5, 6, 3, 2, 5, 4, 5]}
df = pd.DataFrame(data)
df['weekday_name'] = df['weekday_number'].apply(lambda w:(date(2021, 2, 1) + timedelta(days = w)).strftime('%A'))
print(df)
Output
weekday_number weekday_name
0 1 Tuesday
1 2 Wednesday
2 0 Monday
3 3 Thursday
4 4 Friday
5 5 Saturday
6 6 Sunday
7 3 Thursday
8 2 Wednesday
9 5 Saturday
10 4 Friday
11 5 Saturday
You can also use the day_name
array from calendar
:
from calendar import day_name
df['weekday_name'] = df['weekday_number'].apply(lambda w:day_name[w])
Or using map
with day_name
, converting the array into a dict:
df['weekday_name'] = df['weekday_number'].map(dict(enumerate(day_name)))
The results are the same as shown above.
Without a library, you would be best of programming it on a case-by-case basis:
for i in range(len(array)):
if(array[i] == 0):
array[i] = "Monday"
elif(array[i] == 1):
array[i] = "Tuesday"
...
You can also use the calendar module.
import calendar
for i in range(len(array)):
array[i] = calendar.day_name[array[i]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.