Pandas - 数据透视表中总数的百分比

问题描述 投票:0回答:1

有史以来第一篇文章;感谢任何人的帮助!

我曾经在 DAX 中相当快地解决此类问题,但作为 pandas 的新手,我已经在这方面陷入困境了一段时间:

我正在尝试输出一个数据透视表,显示每月(列)和每个城市(行)的签证销售百分比。

和平。

data = {'Month': {0: 'Jan',
  1: 'Jan',
  2: 'Jan',
  3: 'Jan',
  4: 'Feb',
  5: 'Feb',
  6: 'Feb',
  7: 'Feb',
  8: 'Feb'},
 'City': {0: 'Paris',
  1: 'Paris',
  2: 'London',
  3: 'London',
  4: 'Paris',
  5: 'Paris',
  6: 'London',
  7: 'London',
  8: 'Paris'},
 'Card': {0: 'Visa',
  1: 'MasterCard',
  2: 'Visa',
  3: 'MasterCard',
  4: 'Visa',
  5: 'MasterCard',
  6: 'Visa',
  7: 'MasterCard',
  8: 'Visa'},
 ' Amount ': {0: ' $101 ',
  1: ' $567 ',
  2: ' $447 ',
  3: ' $446 ',
  4: ' $926 ',
  5: ' $652 ',
  6: ' $114 ',
  7: ' $88 ',
  8: ' $408 '}}

df = pd.DataFrame.from_dict(data)
df

我尝试过各种数据透视表和分组功能,这让我非常接近,但离我需要的却很远。我只是习惯在 Excel 中创建“度量”,我可以将其添加到数据透视表中,就像常规维度或事实一样。

再次感谢任何让我摆脱困境的人。

python pandas group-by pivot-table percentage
1个回答
0
投票

据我从您的解释中了解到,您想检查每个城市的签证付款百分比或与签证-万事达卡比较百分比进行比较。

对于第一个。首先,将

Amount
列转换为数字。因此,为此我从您的数据中删除了“$”符号。之后,过滤 df 中的 Visa 交易。然后,使用
group_by
表示月份和城市,并计算每个月的 Visa 总销售额。最后,旋转表格,将
Month
作为列,将
City
作为行。在最后一部分中,使用
pivot_table.columns.name = None

从表格中删除了月份标签
df = pd.DataFrame.from_dict(data)

df['Amount'] = df['Amount'].str.replace('$', '',regex=True).str.strip().astype(float)

visa_df = df[df['Card'] == 'Visa']

grouped = visa_df.groupby(['Month', 'City']).agg({'Amount': 'sum'})

grouped['% of Visa Sales'] = grouped.groupby('Month', group_keys=False).apply(lambda x: x / x.sum() * 100)
grouped.reset_index(inplace=True)

pivot_table = grouped.pivot(index='City', columns='Month', values='% of Visa Sales')

pivot_table.columns.name = None

输出是这样的:

              Feb        Jan
City
London   7.872928  81.569343
Paris   92.127072  18.430657

对于我所理解的签证的解决方案--高手比较。

该解决方案的步骤:

    1. 使用

      group_by
      按月、城市、卡进行分组并计算 每个月城市和卡类型的总销售额。

    2. 使用

      pivot_table
      获得所需的桌子。

    3. 计算 Visa 销售额占总销售额的百分比 每个月内的每个城市,仅选择所需的列

最终代码是这样的。

df = pd.DataFrame.from_dict(data)

df['Amount'] = df['Amount'].str.replace('$', '',regex=True).str.strip().astype(float)

visa_master_df = df[df['Card'].isin(['Visa', 'MasterCard'])]

grouped = visa_master_df.groupby(['Month', 'City', 'Card']).agg({'Amount': 'sum'}).reset_index()

print(grouped)

pivot_table = grouped.pivot_table(index=['City'], columns=['Month', 'Card'], values='Amount', fill_value=0)

for month in ['Jan', 'Feb']:
    pivot_table[('% of Visa Sales', month)] = (pivot_table[(month, 'Visa')] / (pivot_table[(month, 'Visa')] + pivot_table[(month, 'MasterCard')])) * 100

result = pivot_table[[('% of Visa Sales', 'Jan'), ('% of Visa Sales', 'Feb')]].round(2)
result.columns = ['Jan', 'Feb']
print(result)

输出就像

          Jan    Feb
City
London  50.06  56.44
Paris   15.12  67.17
© www.soinside.com 2019 - 2024. All rights reserved.