Pandas - Convert a categorical column to binary encoded form

Viewed 6942

I have a dataset that looks like so -

     yyyy      month        tmax         tmin
0    1908    January         5.0         -1.4
1    1908   February         7.3          1.9
2    1908      March         6.2          0.3
3    1908      April         7.4          2.1
4    1908        May        16.5          7.7
5    1908       June        17.7          8.7
6    1908       July        20.1         11.0
7    1908     August        17.5          9.7
8    1908  September        16.3          8.4
9    1908    October        14.6          8.0
10   1908   November         9.6          3.4
11   1908   December         5.8         -0.3
12   1909    January         5.0          0.1
13   1909   February         5.5         -0.3
14   1909      March         5.6         -0.3
15   1909      April        12.2          3.3
16   1909        May        14.7          4.8
17   1909       June        15.0          7.5
18   1909       July        17.3         10.8
19   1909     August        18.8         10.7
20   1909  September        14.5          8.1
21   1909    October        12.9          6.9
22   1909   November         7.5          1.7
23   1909   December         5.3          0.4
24   1910    January         5.2         -0.5
...

It has four variables - yyyy, month, tmax(maximum temperature) and tmin

I want to use the month column as a variable while predictions and so want to convert it to its binary encoded version. Essentially, I want to add twelve variables to the dataset named January until December and if a particular row has month as "January" then the column January should be marked as 1 and the remaining of the newly added 11 columns should be 0.

I looked into pivot tables but that doesn't help my cause. Any ideas on how to do this in a simple elegant way?

2 Answers
Related