2

I wrote a function to determine the weekday. When I try to apply it to my data frame face the following error.

data['date'].head() 

0    2016-01-01
1    2016-01-01
2    2016-01-01
3    2016-01-01
4    2016-01-01

def weekday_determination(col):
    year, month, day = (int(x) for x in col.split('-'))
    ans = datetime.date(year, month, day)
    return ans.strftime('%A')

data['week_day'] = data['date'].apply(weekday_determination, axis=1)

I face the following error:

TypeError: weekday_determination() got an unexpected keyword argument 'axis'

IanS
  • 15,771
  • 9
  • 60
  • 84
  • 1
    `data['date'].apply(weekday_determination)` works for me, without the `axis=1` – anky Jun 27 '19 at 08:04
  • how is it possible as we do not have any index named 'date'? Furthermore, I need to apply for the whole column, this is why I add 'axis =1' – amirhossein Jun 27 '19 at 08:26

1 Answers1

2

Here is better use to_datetime with Series.dt.day_name:

data['week_day'] = pd.to_datetime(data['date']).dt.day_name()

print (data)
         date week_day
0  2016-01-01   Friday
1  2016-01-01   Friday
2  2016-01-01   Friday
3  2016-01-01   Friday
4  2016-01-01   Friday

In your solution is used Series.apply, so no parameter axis:

data['date'] = data['date'].apply(weekday_determination)

Possible solution with DataFrame.apply:

data['week_day'] = data.apply(lambda x: weekday_determination(x['date']), axis=1)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252