2

I am extracting features to look for the weekdays. What I have so far is this:

days = {0:'Mon', 1: 'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'}
data['day_of_week'] = data['day_of_week'].apply(lambda x: days[x])
data['if_Weekday'] = np.where( (data['day_of_week'] == 'Mon') | (data['day_of_week'] == 'Tues') | (data['day_of_week'] == 'Wed') | (data['day_of_week'] == 'Thurs') | (data['day_of_week'] == 'Friday'), '1', '0')

This code will assign Mon-Fri as a 1 and Sat-Sun as a 0. However, I would like to assign different values for the weekdays. For instance, Mon = 1, Tues = 2, Wed = 3, Thurs = 4, Fri = 5 and Sat and Sun should both equal 0.

Any help would be much appreciated.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
ALK
  • 87
  • 1
  • 2
  • 9

2 Answers2

0

OK I think the easiest thing here is to use np.where to test whether the weekday is greater than or equal to 5 and if so assign 0, else return the weekday value and add 1 to it:

In [21]:
df['is_weekday'] = np.where(df['weekday'] >= 5, 0, df['weekday'] + 1)
df
Out[21]:
       dates  weekday  is_weekday
0 2016-01-01        4           5
1 2016-01-02        5           0
2 2016-01-03        6           0
3 2016-01-04        0           1
4 2016-01-05        1           2
5 2016-01-06        2           3
6 2016-01-07        3           4
7 2016-01-08        4           5
8 2016-01-09        5           0
9 2016-01-10        6           0
EdChum
  • 376,765
  • 198
  • 813
  • 562
0

I think you can use mask:

data = pd.DataFrame({'day_of_week':[0,1,2,3,4,5,6]})

#original column to new, add 1
data['if_Weekday'] = data['day_of_week'] + 1

#map days if necessary
days = {0:'Mon', 1: 'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'}
data['day_of_week'] = data['day_of_week'].map(days)

#correct weekend days
data['if_Weekday'] = data['if_Weekday'].mask(data['if_Weekday'] >= 6, 0)

print (data)
  day_of_week  if_Weekday
0         Mon           1
1        Tues           2
2         Wed           3
3       Thurs           4
4         Fri           5
5         Sat           0
6         Sun           0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252