'Converting existing dataframe as per requirement

I have following dataframe as given below:

ID   Year-mo  procedure_code   no_of_procedure 
1    Jan-2010   I06              100  
1    Feb-2010   I06              200
2    Mar-2010   I06              300
2    Apr-2010   I06              400

I need to convert above dataframe into format such that procedure_code column values becomes individual columns with number no_of_procedure as their column values.

Expected output format given below:

ID   Year-mo    I06   
1    Jan-2010   100   
2    Feb-2010   200
3    Mar-2010   300
4    Apr-2010   400


Solution 1:[1]

This looks like a modified pivot where you would reset the ID, but the logic is not fully clear.

From my current understanding, I would use:

(df
 .assign(ID=df.groupby('procedure_code').cumcount().add(1))
 .pivot(index=['ID', 'Year-mo'],
        columns='procedure_code',
        values='no_of_procedure')
 .reset_index().rename_axis(columns=None)
)

output:

   ID   Year-mo  I06
0   1  Jan-2010  100
1   2  Feb-2010  200
2   3  Mar-2010  300
3   4  Apr-2010  400

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway