Search code examples
pythonpandasvectorizationone-hot-encoding

One Hot Encoding Single Categorical Numerical Column


I´m looking to encode a categorical numerical column. I´m seeing a lot of encoding from string-type categorical columns, but not when already transform in numerical.

My goal is to convert this pandas dataframe:

+---------+
|year|hour|
|2018|1|
|2018|3|
|2019|4|
|2019|4|
+------+

To:

+-----------------------------------------+
|year_2018|year_2019|hour_1|hour_3|hour_4|
|1|0|1|0|0|
|1|0|0|1|0|
|0|4|0|0|1|
|0|1|0|0|1|
+---------+

Solution

  • You need pd.get_dummies

    df = pd.DataFrame({'year':[2018,2018,2019,2019], 'hour':[1,3,4,4]})
    
    print(pd.get_dummies(df, columns=['year','hour'], drop_first=False))
    

    Output:

      year_2018  year_2019  hour_1  hour_3  hour_4                                                                                                                   
    0          1          0       1       0       0                                                                                                                   
    1          1          0       0       1       0                                                                                                                   
    2          0          1       0       0       1                                                                                                                   
    3          0          1       0       0       1