Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
- ... "bar", "bar", "bar", "bar"],
- ... "B": ["one", "one", "one", "two", "two",
- ... "one", "one", "two", "two"],
- ... "C": ["2017", "2017", "2018", "2017",
- ... "2018", "2017", "2018", "2017",
- ... "2017"],
- ... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7]})
- dataf = df.pivot_table(values="D", index=["A","B"], columns=["C"], aggfunc=np.sum, margins=True, dropna=True)
- dataf
- C 2017 2018 All
- A B
- bar one 4.0 5.0 9
- two 13.0 NaN 13
- foo one 3.0 2.0 5
- two 3.0 3.0 6
- All 23.0 10.0 33
- In [71]: dataf['new'] = dataf['2018'] / dataf['2017']
- In [72]: dataf
- Out[72]:
- C 2017 2018 All new
- A B
- bar one 4.0 5.0 9 1.250000
- two 13.0 NaN 13 NaN
- foo one 3.0 2.0 5 0.666667
- two 3.0 3.0 6 1.000000
- All 23.0 10.0 33 0.434783
Add Comment
Please, Sign In to add comment