I would like to Unpivot/unstack my dataframe. My df is like:
a=pd.DataFrame(columns=['Name','Title','Status'],data=[['John','Course1','Finished'],['Mike','Course2','Accepted'],['Jim','Course1','Accepted'],['Jhonny','Course3','Rejected'],['Jhonny','Course3','Accepted']])
And I need it to be like:
I have tried with pd.melt and pd.unstack() but not with the desired results. Can you give me a hand? Thanks
CodePudding user response:
You could use pivot_table()
a.pivot_table(index='Name', columns=['Title'], values='Status', aggfunc='first')
prints:
Course1 Course2 Course3
Name
Jhonny Accepted NaN Rejected
Jim Accepted NaN NaN
John Finished NaN NaN
Mike NaN Accepted NaN
I think you have a typo in your sample DF above. I think it should be:
a = pd.DataFrame(columns=['Name','Title','Status'], data=[['John','Course1','Finished'],['Mike','Course2','Accepted'],['Jim','Course1','Accepted'],['Jhonny','Course3','Rejected'],['Jhonny','Course1','Accepted']])