python - Pandas Pivot 在一列上使用多索引
问题描述
我想基于一列旋转一个表,索引为两列,
数据集:
uid interaction date
1 like 2016-12-04
1 like 2016-12-05
1 comment 2016-12-05
1 like 2016-12-05
2 like 2016-12-04
2 like 2016-12-05
2 comment 2016-12-05
2 like 2016-12-05
使用 uid 和日期我想在特定日期为特定 uid 发生的交互次数。
最后结果:
uid like comment date
1 1 0 2016-12-04
1 2 1 2016-12-05
2 1 0 2016-12-04
2 2 1 2016-12-05
我尝试过的方法:
doc_social_interaction.pivot_table(index = ['uid','date'],columns = 'interaction', aggfunc=sum)
解决方案
你很接近,需要GroupBy.size
计数:
df1 = df.pivot_table(index=['uid','date'],columns='interaction',aggfunc='size',fill_value=0)
另一个解决方案:
df1 = df.groupby(['uid','date','interaction']).size().unstack(fill_value=0)
df1 = df.groupby(['uid','date'])['interaction'].value_counts().unstack(fill_value=0)
df1 = pd.crosstab([df['uid'],df['date']], df['interaction'])
print (df1)
interaction comment like
uid date
1 2016-12-04 0 1
2016-12-05 1 2
2 2016-12-04 0 1
2016-12-05 1 2
最后进行一些数据清理:
df1 = df1.reset_index().rename_axis(None, 1)
print (df1)
uid date comment like
0 1 2016-12-04 0 1
1 1 2016-12-05 1 2
2 2 2016-12-04 0 1
3 2 2016-12-05 1 2
推荐阅读
- powershell - 如何使用 TaskScheduler 保持 Powershell 脚本持续运行?
- python - 如何将 Imagemagick 转换为 Wand?
- snowflake-cloud-data-platform - Extract string after first '/' using snowflake query
- python - 根据 Python 中的时间戳日期创建多个数据帧
- mysql - mysql workbench中knex的查询结果不收敛
- r - 检测连续单词与数字并移动它们的功能?
- javascript - React Native Expo - 在变量赋值之前设置初始值
- node.js - 我的节点和 npm 已经是最新版本
- angular11 - 搜索结果仅在第二次点击时显示,Angular 11
- java - 计算对象的非空数