You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为多层索引DataFrame添加Productivity子列

解决方案

假设你的DataFrame采用多层列索引(MultiIndex)(顶层为角色名称如Admin,底层为produktiv、unproduktiv),可以按以下步骤为每个角色添加Productivity子列:

核心代码实现

import pandas as pd

# 遍历所有唯一角色
for role in df.columns.get_level_values(0).unique():
    # 获取当前角色的两个子列数据
    produktiv = df[(role, 'produktiv')]
    unproduktiv = df[(role, 'unproduktiv')]
    
    # 计算Productivity,同时处理除以0的异常情况
    total = produktiv + unproduktiv
    productivity = produktiv / total * 100
    # 若总和为0,将结果设为0(也可根据需求改为pd.NA)
    productivity = productivity.where(total != 0, 0)
    
    # 将新列添加到对应角色的子列下
    df[(role, 'Productivity')] = productivity

# 重新排序列,让每个角色的三个子列排列在一起
df = df.sort_index(axis=1)

针对扁平化列名的适配方案

如果你的列是扁平化命名(如Admin_produktiv、Admin_unproduktiv),可以用以下代码调整:

# 提取所有唯一角色名称
roles = set(col.split('_')[0] for col in df.columns)

for role in roles:
    produktiv_col = f"{role}_produktiv"
    unproduktiv_col = f"{role}_unproduktiv"
    
    total = df[produktiv_col] + df[unproduktiv_col]
    df[f"{role}_Productivity"] = df[produktiv_col] / total * 100
    df[f"{role}_Productivity"] = df[f"{role}_Productivity"].where(total != 0, 0)

# 可选:按角色分组排序列
df = df.reindex(sorted(df.columns, key=lambda x: x.split('_')[0]), axis=1)

关键说明

  • 计算逻辑严格遵循你给出的公式:Productivity = Produktiv / (Produktiv + Unproduktiv) * 100
  • 加入了总和为0的判断,避免运行时出现除以0的错误
  • 最后排序列的操作可让同角色的三个子列相邻,提升数据可读性

内容的提问来源于stack exchange,提问作者dat boi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:55:15