在熊猫Pivot_table中添加和计算值

时间:2018-06-20 19:31:03

标签: python pandas pivot-table

我有带有代码的数据透视表:

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

我想在2018年之后添加新列,以计算2018/2017年的价值。我该怎么办?

0 个答案:

没有答案