Guest User

Untitled

a guest
Jun 21st, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
  2. ... "bar", "bar", "bar", "bar"],
  3. ... "B": ["one", "one", "one", "two", "two",
  4. ... "one", "one", "two", "two"],
  5. ... "C": ["2017", "2017", "2018", "2017",
  6. ... "2018", "2017", "2018", "2017",
  7. ... "2017"],
  8. ... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7]})
  9. dataf = df.pivot_table(values="D", index=["A","B"], columns=["C"], aggfunc=np.sum, margins=True, dropna=True)
  10. dataf
  11. C 2017 2018 All
  12. A B
  13. bar one 4.0 5.0 9
  14. two 13.0 NaN 13
  15. foo one 3.0 2.0 5
  16. two 3.0 3.0 6
  17. All 23.0 10.0 33
  18.  
  19. In [71]: dataf['new'] = dataf['2018'] / dataf['2017']
  20.  
  21. In [72]: dataf
  22. Out[72]:
  23. C 2017 2018 All new
  24. A B
  25. bar one 4.0 5.0 9 1.250000
  26. two 13.0 NaN 13 NaN
  27. foo one 3.0 2.0 5 0.666667
  28. two 3.0 3.0 6 1.000000
  29. All 23.0 10.0 33 0.434783
Add Comment
Please, Sign In to add comment