Advertisement
elena1234

pivot and unstack in Python

May 22nd, 2022 (edited)
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1. # We have df with three columns: "Country", "Medal" and "Count":
  2.  
  3. new_df = df.pivot(index = "Country", columns = "Medal", values = "Count").fillna(0)
  4. # new_df has for the index "Contry" and three columns: "Bronze", "Silver" and "Gold" with values
  5.  
  6. new_df = df.set_index(['Country', 'Medal']).unstack(fill_value = 0)
  7. # new_df has for the index "Contry" and three columns: "Bronze", "Silver" and "Gold" with values
  8.  
  9. ################################################################################################
  10. # table2 has additional column "Year" and we want to unstack the column "Medal"
  11. # we can use only unstack()
  12. table2.groupby(["Country", "Year", "Medal"]).Count.sum().unstack().fillna(0)
  13.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement