Menu Close

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

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.

Posted in Python, Python Answers