在熊猫的数据透视表中插入占总价值的百分比

时间:2019-04-04 11:27:51

标签: python pandas pivot-table

我有3家公司A,B和C,其2018年每个季度的销售数据分为计算机和打印机类别。

df = pd.DataFrame({"Fiscal Quarter": ["FY18-Q1", "FY18-Q1", "FY18-Q1", "FY18-Q1", "FY18-Q1", "FY18-Q1",
                                      "FY18-Q2", "FY18-Q2", "FY18-Q2", "FY18-Q2", "FY18-Q2", "FY18-Q2",
                                      "FY18-Q3", "FY18-Q3", "FY18-Q3", "FY18-Q3", "FY18-Q3", "FY18-Q3",
                                      "FY18-Q4", "FY18-Q4", "FY18-Q4", "FY18-Q4", "FY18-Q4", "FY18-Q4"],
                   "Company": ["A", "A", "B", "B", "C", "C",
                               "A", "A", "B", "B", "C", "C",
                               "A", "A", "B", "B", "C", "C",
                               "A", "A", "B", "B", "C", "C"],
                   "Category": ["Computers", "Printers", "Computers", "Printers", "Computers", "Printers",
                                "Computers", "Printers", "Computers", "Printers", "Computers", "Printers",
                                "Computers", "Printers", "Computers", "Printers", "Computers", "Printers",
                                "Computers", "Printers", "Computers", "Printers", "Computers", "Printers"],
                   "Sales": [300, 350, 1000, 700, 2500, 2800,
                             450, 200, 1100, 720, 2400, 2100,
                             600, 330, 850, 1200, 2400, 2000,
                             520, 400, 900, 700, 2000, 2200]})

https://github.com/currentlyunknown/sampledata/blob/master/sampledata.csv

我不仅希望将“价值”视为每个公司的$销售额,而且还希望将其作为一个季度与总销售额(A + B + C)的百分比比较,以公司A为例:

               FY18-Q1          FY18-Q2
Computers      300              450
Printers       350              400

所需的输出将如下所示:

               FY18-Q1          FY18-Q2
Computers      300              450
               30%              40%
Printers       350              400
               25%              27%

到目前为止,我必须使用以下方法为每个公司准备一个带有['%of Total']列的df:

total = df.groupby(['Fiscal Quarter', 'Category']).sum().rename(columns={"Sales": "Total Sales"})

df = df.merge(total, on=['Fiscal Quarter', 'Category'])

df['% of Total'] = (df['Sales'] / df['Total Sales'])

df = df.drop(['Total Sales'], axis=1)

我创建数据透视表以分别查看每个公司的销售数据:

dfa = df[df['Company']=='A']

A = pd.pivot_table(
    dfa,
    index=['Category'],
    columns=['Fiscal Quarter'],
    values=['Sales', '% of Total'],
    aggfunc=np.sum
    ).reset_index()

A.columns = A.columns.droplevel([0])
A = A.reset_index().rename_axis(None, axis=1)

但我最终得到:

               FY18-Q1          FY18-Q2          FY18-Q1          FY18-Q2
Computers      300              450              30%              40%
Printers       350              400              25%              27%

现在,如何以所需的方式旋转它?

1 个答案:

答案 0 :(得分:0)

  1. 计算表副本中的总和(groupby + sum)
  2. 按公司名称合并两个表(您将获得一个额外的总销售额列)
  3. 计算总销售额与确切的Q销售额之间的百分比
  4. 枢轴