Using Pandas I've invoked groupby on my dataframe and obtained the following:
>>>grouped = df.groupby(['cid'])
for key, gr in grouped:
print(key)
print(gr)
Out: cid price
121 12
121 10
121 9
I want to have each group pivoted like:
cid price1 price2 price3
121 12 10 9
What is the correct way to do this with Pandas?
Assuming you have a frame looking like
Then I think you can get what you want by combining
groupby
andpivot
:which gives
Aside: sticking numbers after the end of strings, e.g. "price5", is usually not a good idea. You can't really work with them, they don't sort the way you'd expect, etc.
First, we create a column showing what index something is in the price:
Then we
pivot
:Then we fix the columns:
And finally we reset the index: