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

Pandas如何按name生成唯一行并拆分channel为多列统计对应value总和

实现方案

核心思路

直接用Pandas的透视表功能完成分组汇总+宽表转换,再衍生出标识列即可,你的原始思路缺少分组求和和行列转换的步骤,所以无法得到预期结构。

完整可运行代码

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    "name": ["a1", "a2", "a1", "a1", "a3", "a3"], 
    "channel": ["branch", "online", "branch", "online", "branch", "branch"], 
    "value": [150, 200, 120, 100, 120, 200]
})

# 1、透视表按name分组,计算各渠道的value总和,缺失值填充0
pivot_df = df.pivot_table(
    index="name",
    columns="channel",
    values="value",
    aggfunc="sum",
    fill_value=0
).reset_index()

# 2、生成channel存在标识列(yes/no)
for channel_name in ["branch", "online"]:
    pivot_df[f"channel_{channel_name}"] = pivot_df[channel_name].map(lambda x: "yes" if x > 0 else "no")

# 3、重命名汇总列、调整列顺序匹配预期
pivot_df = pivot_df.rename(columns={
    "branch": "branch_value",
    "online": "online_value"
})
result = pivot_df[["name", "channel_branch", "channel_online", "branch_value", "online_value"]]

print(result)

输出验证

运行后输出结果和你给出的预期完全一致:

name channel_branch channel_online  branch_value  online_value
0   a1            yes            yes           270           100
1   a2             no            yes             0           200
2   a3            yes             no           320             0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:36:03