Skip to content
Advertisement

Merging pandas get_dummies back to categorical values

I have a pandas dataframe which I have one hot encoded with get_dummies, the data previously had a ‘type’ column which contained the values small_airport, large_airport, medium_airport, I split the type column in to each different type of airport with 1s and 0s where the frequencies matched. After using get_dummies, it looks a bit like this:

JavaScript

Basically I need now to ‘undo’ the get_dummies and get the type column back. I have looked at loads of similar questions and have tried using.

JavaScript

but I can’t seem to get the result I need, or I am not understanding the answers enough to implement them in to my own project.

I really hope that is clear! Any help would be massively appreciated!

Advertisement

Answer

Test df:

JavaScript

Code:

JavaScript

Output:

JavaScript

For your case, you may want to explicitly choose the columns you’re working with, aka:

JavaScript

And then if you want to simplify the results:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement