查找熊猫数据透视表数据帧中特定索引名称的所有记录的总和



我有熊猫数据透视表数据框,如下所示:

Account ACC1    ACC2    ACC3    GRAND TOTAL
Product             
PROD1   2       3       4       9
PROD2   3       5       7       15
REFUND  2       3       8       13

在数据透视表代码中,我使用了index = "Product"margins_name="GRAND TOTAL".

我想找到退款金额,我该怎么做?或索引名称="退款"的"总计"值,即"13"。 我在下面使用来创建数据透视表:

df_pivot = pd.pivot_table(df1,values="cost",index = "Product", columns="Account",
margins = True, margins_name="GRAND TOTAL",aggfunc=np.sum,fill_value=0)

使用 .loc 选择行,然后选择列并检索值。

df_pivot.loc['REFUND',"GRAND TOTAL"]

例:

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two",
"one", "one", "two", "two"],
"C": ["small", "large", "large", "small",
"small", "large", "small", "small",
"large"],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
table = pd.pivot_table(df, values='D', index=['A'],
columns=['C'], margins = True, margins_name="GRAND TOTAL",aggfunc=np.sum,fill_value=0)
table
C          large    small   GRAND TOTAL
A           
bar           11       11       22
foo            4        7       11
GRAND TOTAL   15       18       33
table.loc['foo',"GRAND TOTAL"]
11

最新更新