0
data = {'day_of_the_week':  ['Mon', 'Tue','Wed','Thu','Fri','Sat','Sun'], 'day': [13, 23,7,14,25,16,17],
       'month':['January','February','March','April','May','June','July']}
df = pd.DataFrame (data, columns = ['day_of_the_week','day','month'])

I would like to convert the categorical value in the column 'day_of_the_week' to numerical, such as: Mon --> 1, Wed --> 3, Fri --> 5, ...

The following code returns no error, however, all the value in df['day_of_the_week_code'] returns 0.

df["day_of_the_week_code"] = np.where(df["day_of_the_week"].str.contains("Mon"), 1,0)
df["day_of_the_week_code"] = np.where(df["day_of_the_week"].str.contains("Tue"), 2,0)
df["day_of_the_week_code"] = np.where(df["day_of_the_week"].str.contains("Wed"), 3,0)
df["day_of_the_week_code"] = np.where(df["day_of_the_week"].str.contains("Thu"), 4,0)
df["day_of_the_week_code"] = np.where(df["day_of_the_week"].str.contains("Fri"), 5,0)
df["day_of_the_week_code"] = np.where(df["day_of_the_week"].str.contains("Sat"), 6,0)
df["day_of_the_week_code"] = np.where(df["day_of_the_week"].str.contains("Sun"), 7,0)
Ben.T
  • 29,160
  • 6
  • 32
  • 54
Luc
  • 737
  • 1
  • 9
  • 22

1 Answers1

2

You can use map:

dow_dict = {'Mon': 1, 'Tue': 2, 'Wed': 3, 'Thu': 4, 'Fri': 5, 'Sat': 6, 'Sun': 7}
df['day_of_the_week_code'] = df.day_of_the_week.map(dow_dict)
Wouter
  • 3,201
  • 6
  • 17