So I have this data which which has the 12 months as below: enter image description here

When I one-hot encode it using pd.get_dummies the result is this: enter image description here You see that the new columns are ordered alphabetically losing the months order, which makes reading the data hard. Is there any way to preserve the order?


1 Answer 1


One option is to create a separate dataframe with the dummy variables, reorder it, and concat it with the original dataframe.

df = pd.DataFrame({'month': ['jan', 'feb', 'jan', 'march', 'jan']})
dummies = pd.get_dummies(df.month)
dummies = dummies[['jan', 'feb', 'march']]
pd.concat([df, dummies], axis=1)

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.