如何使用Pandas将两个聚合表合并为嵌套形式并自定义列名展示?
Pandas实现嵌套式合并层级展示
可以实现这种嵌套层级的合并展示,核心思路是将年份汇总表和品牌明细表统一格式后合并,通过多层索引实现年份下嵌套品牌数据的结构,同时格式化字段满足展示需求。
实现步骤
- 统一两个聚合表的列名,简化为友好名称
- 处理年份汇总表的总品牌数字段,格式化为「X Brands」的字符串
- 为汇总表添加专属标识,方便区分汇总行与品牌行
- 合并两个表后设置多层索引,按年份和标识排序,实现层级展示
完整代码示例
1. 准备样例数据
import pandas as pd # 模拟业务样例数据 data = { 'year': [2022, 2022, 2022, 2023, 2023, 2023], 'brand_name': ['A', 'B', 'A', 'C', 'C', 'D'], 'user_id': [1, 2, 1, 3, 4, 5], 'story_id': [101, 102, 101, 103, 104, 105], 'video_id': [201, 202, 201, 203, 204, 205], 'node_key': [301, 302, 301, 303, 304, 305] } df = pd.DataFrame(data)
2. 生成原始聚合表
# 按年份聚合的总览表 table1 = df.groupby('year').agg( Total_Brands=('brand_name', 'nunique'), Total_Users=('user_id', 'nunique'), Total_Stories=('story_id', 'nunique'), Total_Sessions=('video_id', 'nunique'), Total_Nodes=('node_key', 'nunique') ).reset_index() # 按年份+品牌聚合的明细表 table2 = df.groupby(['year','brand_name']).agg( Total_Users=('user_id', 'nunique'), Total_Stories=('story_id', 'nunique'), Total_Sessions=('video_id', 'nunique'), Total_Nodes=('node_key', 'nunique') ).reset_index()
3. 统一两个表的格式
# 处理年份总览表:格式化品牌数字段,重命名列,添加汇总标识 table1['Brands'] = table1['Total_Brands'].apply(lambda x: f"{x} Brands") table1 = table1.rename(columns={ 'Total_Users': 'Users', 'Total_Stories': 'Stories', 'Total_Sessions': 'Sessions', 'Total_Nodes': 'Nodes' }) # 添加汇总行专属标识 table1['brand_name'] = 'Yearly Summary' # 保留需要的字段 table1 = table1[['year', 'brand_name', 'Brands', 'Users', 'Stories', 'Sessions', 'Nodes']] # 处理品牌明细表:重命名列,补充品牌名字段 table2 = table2.rename(columns={ 'Total_Users': 'Users', 'Total_Stories': 'Stories', 'Total_Sessions': 'Sessions', 'Total_Nodes': 'Nodes' }) table2['Brands'] = table2['brand_name']
4. 合并并生成嵌套层级结构
# 合并两个表 combined_df = pd.concat([table1, table2], ignore_index=True) # 设置多层索引,实现年份下嵌套品牌的层级展示 combined_df = combined_df.set_index(['year', 'brand_name']) # 排序:确保每个年份的汇总行排在最上方 combined_df = combined_df.sort_index(level=['year', 'brand_name'], key=lambda x: x != 'Yearly Summary')
5. 查看最终结果
print(combined_df)
输出结果示例:
Brands Users Stories Sessions Nodes year brand_name 2022 Yearly Summary 2 Brands 2 2 2 2 A A 1 1 1 1 B B 1 1 1 1 2023 Yearly Summary 2 Brands 3 3 3 3 C C 2 2 2 2 D D 1 1 1 1
内容的提问来源于stack exchange,提问作者user13642402
相关产品推荐
相关产品推荐

