python-3.x - 使用 pd.pivot_table 中的现有列初始化 pd.pivot_table 中的新列
问题描述
我使用 pd.read_csv 将表导入 python,如下所示
我需要在此表上执行 3 项活动,如下所示
- 使用 group by 计算每种类型的免费应用程序和付费应用程序的数量。
我编写了以下代码以获得所需的输出`
df.groupby(['prime_genre','Subscription'])[['id']].count()`
输出:
- 将结果从 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')
输出:
现在我需要初始化一个列“Total”,该列捕获数据透视表本身中“免费应用程序”和“付费应用程序”的总和
我还需要再初始化两列 perc_free 和 perc_paid 来显示数据透视表本身中免费应用程序和付费应用程序的百分比
我怎么去3和4?
解决方案
假设以下数据透视表名为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
推荐阅读
- javascript - 如何实现 div 块高度的动态计算?
- sql - 如何根据两个不同表中的相反值编写 SQLite 查询?
- react-native - React Native - 即使编写了正确的代码,选择器也没有出现
- regex - RegEx - 是否可以仅使用 RegEx 引擎进行递归替换?条件搜索替换
- c# - 实例化指向另一个对象方向的预制件
- python - 如何使用正则表达式在熊猫数据框中获取字符串
- dns - 如何在网络解决方案 CNAME 中正确设置别名以使用 Amazon s3 存储桶?
- python-3.x - 如何在不停止/暂停生产者脚本的情况下释放一批 celery 后端资源?
- node.js - 向 node.js 事件库中的异步侦听器发送时如何修复空参数?
- javascript - 基于滚动位置的 div 位置