Categories
Python Answers

How to do long to wide reshape, by two variables with Python Pandas?

Spread the love

Sometimes, we want to do long to wide reshape, by two variables with Python Pandas.

In this article, we’ll look at how to do long to wide reshape, by two variables with Python Pandas.

How to do long to wide reshape, by two variables with Python Pandas?

To do long to wide reshape, by two variables with Python Pandas, we can use groupby with cumcount.

For instance, we write

df['idx'] = df.groupby('Salesman').cumcount()

to call groupby to group values by the Salesman column.

And then call cumcount to return the cumulative counts of the grouped values.

Conclusion

To do long to wide reshape, by two variables with Python Pandas, we can use groupby with cumcount.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *