How to apply a function on a column

Viewed 198

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'

1 Answers

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)
Related