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

如何将pandas DataFrame行转列,按ChannelPartnerID分组转换Brand为销售列

你可以直接用pandas的pivot_table方法实现需求,完整可运行代码如下:

import pandas as pd

# 构造原始DataFrame
data = {'ChannelPartnerID': [10000, 10000, 10000, 10000, 10000, 10001, 10001, 10001, 10002, 10002],
        'Brand': ['B1', 'B2', 'B3', 'B4', 'B5', 'B1', 'B2', 'B5', 'B1', 'B4'],
        'Sales': [29630, 38573, 1530, 21793, 7155, 26477, 42158, 14612, 6649, 6468]}
df = pd.DataFrame(data)

# 透视转换实现行列转换
res = df.pivot_table(
    index='ChannelPartnerID',
    columns='Brand',
    values='Sales',
    aggfunc='sum',
    fill_value=0
).reset_index()

# 给品牌列统一加_Sales后缀
res.columns = [f"{col}_Sales" if col.startswith('B') else col for col in res.columns]

# 补充需要的B6、B7销售额列,无数据默认填充0
for add_col in ['B6_Sales', 'B7_Sales']:
    if add_col not in res.columns:
        res[add_col] = 0

# 调整列顺序匹配你的期望输出
res = res[['ChannelPartnerID', 'B1_Sales', 'B2_Sales', 'B3_Sales', 'B4_Sales', 'B5_Sales', 'B6_Sales', 'B7_Sales']]

print(res)

运行上述代码输出的结果和你要求的格式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 19:30:02