Skip to content
Advertisement

How can I make a column into rows with pandas with a dynamic number of columns?

I am trying to convert a column of values into separate columns using pandas in python. So I have columns relating to shops and their products and the number of products each shop has could be different. For example:

JavaScript

What I am trying to achieve would look something like this:

JavaScript

If there are any shops that have more than 3 products, I would need more columns to be created for them dynamically. Any ideas or suggestions are appreciated! Thanks!

Advertisement

Answer

Use GroupBy.cumcount for counter with reshape by Series.unstack:

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