使用Python在Pandas数据框中创建星期几列

使用Python在Pandas数据框中创建星期几列,第1张

使用Python在Pandas数据框中创建星期几列 pandas0.23+

使用

pandas.Series.dt.day_name()
,因为
pandas.Timestamp.weekday_name
已弃用:

import pandas as pddf = pd.Dataframe({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})df['my_dates'] = pd.to_datetime(df['my_dates'])df['day_of_week'] = df['my_dates'].dt.day_name()

输出

    my_dates  myvals day_of_week0 2015-01-01       1    Thursday1 2015-01-02       2      Friday2 2015-01-03       3    Saturday
熊猫0.18.1+

正如用户jezrael指出的那样,

dt.weekday_name
已在版本0.18.1中添加了 Pandas
Docs

import pandas as pddf = pd.Dataframe({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})df['my_dates'] = pd.to_datetime(df['my_dates'])df['day_of_week'] = df['my_dates'].dt.weekday_name

输出:

    my_dates  myvals day_of_week0 2015-01-01       1    Thursday1 2015-01-02       2      Friday2 2015-01-03       3    Saturday
原始答案:

用这个:

http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.Series.dt.dayofweek.html

看到这个:

获取Dataframe的Datetime列的工作日/星期几

如果要使用字符串而不是整数,请执行以下 *** 作:

import pandas as pddf = pd.Dataframe({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})df['my_dates'] = pd.to_datetime(df['my_dates'])df['day_of_week'] = df['my_dates'].dt.dayofweekdays = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x])

输出:

    my_dates  myvals day_of_week0 2015-01-01       1       Thurs1 2015-01-02       2         Fri2 2015-01-01       3       Thurs


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5639479.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存