James Eaves James Eaves - 1 year ago 1209
Python Question

Create a day-of-week column in a Pandas dataframe using Python

Create a day-of-week column in a Pandas dataframe using Python

I’d like to read a csv file into a pandas dataframe, parse a column of dates from string format to a date object, and then generate a new column that indicates the day of the week.

This is what I’m trying:

What I’d like to do is something like:

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'

Thank you for your help.

Answer Source

Use this:


See this:

get weekday for Datetime in Pandas DataFrame

If you want a string instead of an integer do something like this:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download