首页 > 解决方案 > 使用 pd.pivot_table 中的现有列初始化 pd.pivot_table 中的新列

问题描述

我使用 pd.read_csv 将表导入 python,如下所示

数据集

我需要在此表上执行 3 项活动,如下所示

  1. 使用 group by 计算每种类型的免费应用程序和付费应用程序的数量。

我编写了以下代码以获得所需的输出`

df.groupby(['prime_genre','Subscription'])[['id']].count()`

输出:

code1_output

  1. 将结果从 1 转换为数据帧,其列为 prime_genre、free、paid 以及具有每个计数的行

我编写了以下代码以获得所需的输出

df1 = df.groupby(['prime_genre','Subscription'])['id'].count().reset_index() df1.pivot_table(index='prime_genre', columns='Subscription', values='id' , aggfunc='sum')

输出:

code2_output

  1. 现在我需要初始化一个列“Total”,该列捕获数据透视表本身中“免费应用程序”和“付费应用程序”的总和

  2. 我还需要再初始化两列 perc_free 和 perc_paid 来显示数据透视表本身中免费应用程序和付费应用程序的百分比

我怎么去3和4?

标签: python-3.xpandasdataframepivot-table

解决方案


假设以下数据透视表名为df2

subscription  free app  paid app
prime_genre                     
book                66        46
business            20        37
catalogs             9         1
education          132       321

pandas.DataFrame.sum您可以使用列 ( )计算总数axis=1。然后除以df2这个总数并乘以 100 得到百分比。您可以使用 为列添加后缀pandas.DataFrame.add_suffix。最后,将所有内容与pandas.concat

total = df2.sum(axis=1)
percent = df2.div(total, axis=0).mul(100).add_suffix(' percent')
df2['Total'] = total
pd.concat([df2, percent], axis=1)

输出:

subscription  free app  paid app  Total  free app percent  paid app percent
prime_genre                                                                
book                66        46    112         58.928571         41.071429
business            20        37     57         35.087719         64.912281
catalogs             9         1     10         90.000000         10.000000
education          132       321    453         29.139073         70.860927

这是获取perc_free/perc_paid名称的变体:

total = df2.sum(axis=1)
percent = (df2.div(total, axis=0)
              .mul(100)
              .rename(columns=lambda x: re.sub('(.*)( app)', r'perc_\1',x))
          )
df2['Total'] = total
pd.concat([df2, percent], axis=1)
subscription  free app  paid app  Total  perc_free  perc_paid
prime_genre                                                  
book                66        46    112  58.928571  41.071429
business            20        37     57  35.087719  64.912281
catalogs             9         1     10  90.000000  10.000000
education          132       321    453  29.139073  70.860927

推荐阅读