0
$\begingroup$

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?

$\endgroup$

1 Answer 1

1
$\begingroup$

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

$\endgroup$

Your Answer

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

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