How to transform my grouped DataFrame column type rows into multiple columns

Question:

I have the following DataFrame:

Id         Category        Amount
900000007  Schuur          8.0
900000009  Garage          24.0
           Dakkapel        5.0
900000015  Schuur          8.0
           Garage          20.0
           Dakkapel        5.0
900000019  Schuur          8.0
           Garage          18.0

So it’s a list of Id’s, a variable list of categories and an amount for each category that exists for that Id.

Now I want it to become like this:

Id         Schuur       Garage    Dakkapel
900000007  8.0          NaN       Nan
900000009  Nan          24.0      5.0
900000015  8.0          20.0      5.0
900000019  8.0          18.0      Nan

So the categories become the name of the columns, with one row for each Id and the amount filled in for each category.
Please help me find the right function for this, thanks!

Asked By: Romy

||

Answers:

If first 2 columns are levels of MultiIndex use Series.unstack with select column Amount:

df1 = df['Amount'].unstack()
Answered By: jezrael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.