Skip to content
Advertisement

Make a new column for each category in a particular column and repeat this for all columns in a Pandas dataframe

I have a dataset like below-:

JavaScript

I want new columns for each category in all columns for each state. An example of a row is below-:

JavaScript

EDIT Data dump of 1st 5 rows as asked-:

JavaScript

Advertisement

Answer

Use pd.get_dummies + Groupby.sum(), as follows:

JavaScript

Result:

JavaScript

If you want to exclude the entries with value NA, you can use:

JavaScript

Result:

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