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

Pandas中如何按文本和日期分组对group、theme列生成0/1标识列

问题原因与解决方案

逻辑错误点

  • 索引选择错误:需求的分组维度是text、dates,但你用唯一值id作为pivot的索引,无法合并相同text、dates的行
  • 方法不匹配需求:pivot适合将单列的唯一值转为列,你需要的是对group、theme两个列分别做独热编码后按分组聚合,原始用法无法实现这个效果

正确实现代码

import pandas as pd

# 原始数据集
df = pd.DataFrame({'id':[1,2,3,4,5,6],
                   'text':['Oh no Monday','Oh no Monday','Gotcha 🇫🇷!',
                           'Coffee, please','Coffee, please','Mails 🌎'],
                   'dates':['2019-05-30T17:48:45+0000','2019-05-30T17:48:45+0000',
                           '2019-05-25T19:40:43+0000','2019-03-30T14:41:20+0000',
                           '2019-03-30T14:41:20+0000','2019-04-10T19:50:49+0000'],
                   'group':['meme','humour','gif','gif','pic','meme'],
                   'theme':['light','light','funny','dark','sad','funny']})

# 1. 对group、theme列做独热编码,直接用枚举值作为列名
df_enc = pd.get_dummies(df, columns=['group', 'theme'], prefix='', prefix_sep='')

# 2. 按text、dates分组聚合:id取分组第一个值,独热列取max(存在对应值则为1)
result = df_enc.groupby(['text', 'dates'], as_index=False).agg(
    id=('id', 'first'),
    **{col: (col, 'max') for col in df_enc.columns if col not in ['id', 'text', 'dates']}
)

# 调整列顺序对齐预期输出
result = result[['id', 'text', 'dates'] + [c for c in result.columns if c not in ['id', 'text', 'dates']]].reset_index(drop=True)
print(result)

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 05:27:04