全部
我的数据集如下所示,我想添加一个列,该列可以将我的最后一列即Day_of_The_week转换为Mon,Tue,Wed。 注意:Day_of_the_week包括5天:星期一,星期二,星期三,星期四,星期五。我检查了link,但不知道如何在数据框中实现
成为python的新手,如果您能提供解释的话,那就太好了!
答案 0 :(得分:1)
calendar.day_name
+ pd.Series.map
您可以构建字典,然后将整数序列映射到日字符串列表:
import pandas as pd
from calendar import day_name
from collections import deque
df = pd.DataFrame({'Day_of_the_week': [2, 3, 4, 4, 5, 6, 6]})
days = deque(day_name)
days.rotate(df['Day_of_the_week'].iat[0]) # rotate days
days_map = dict(enumerate(days)) # construct dictionary
df['Day_Factor'] = df['Day_of_the_week'].map(days_map)
print(df)
Day_of_the_week Day_Factor
0 2 Monday
1 3 Tuesday
2 4 Wednesday
3 4 Wednesday
4 5 Thursday
5 6 Friday
6 6 Friday