小编典典

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

python

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

我想将csv文件读取到pandas数据框中,将一列日期从字符串格式解析为日期对象,然后生成一个新列以指示星期几。

这是我正在尝试的:

我想做的是这样的:

import pandas as pd

import csv

df = pd.read_csv('data.csv', parse_dates=['date']))

df['day-of-week'] = df['date'].weekday()


AttributeError: 'Series' object has no attribute 'weekday'

感谢您的帮助。


阅读 178

收藏
2020-12-20

共1个答案

小编典典

pandas0.23+

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

import pandas as pd


df = 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_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

熊猫0.18.1+

正如用户jezrael指出的那样,dt.weekday_name已在版本0.18.1中添加了 Pandas
Docs

import pandas as pd

df = 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_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

原始答案:

用这个:

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

看到这个:

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

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

import pandas as pd

df = 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.dayofweek

days = {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_week
0 2015-01-01       1       Thurs
1 2015-01-02       2         Fri
2 2015-01-01       3       Thurs
2020-12-20