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

如何将Pandas DataFrame相似条目扁平化 合并独热编码列值为单条记录

解决方法

核心逻辑是按商家唯一标识分组,对Dietary开头的独热编码列取最大值(只要任意一行该字段为1,聚合后就为1),公共字段取相同值即可,具体实现代码如下:

# 方法1:如果索引是商家唯一ID(如示例中索引均为17660)
import pandas as pd

# 区分公共列和哑变量列
common_cols = ['name', 'stars', 'categories']
dummy_cols = [col for col in df.columns if col.startswith('Dietary_')]

# 配置聚合规则后分组计算
agg_rule = {col: 'first' for col in common_cols}
agg_rule.update({col: 'max' for col in dummy_cols})
result = df.groupby(level=0).agg(agg_rule).reset_index()
# 方法2:如果没有用索引存商家ID,直接用公共字段做分组依据
result = df.groupby(common_cols, as_index=False)[dummy_cols].max()

两种方法都能得到你需要的压缩后结果,原理是同一个商家的公共字段值完全一致,取first/last都不会改变取值;哑变量列取最大值可以把该商家所有行里出现过的1都合并到最终行里,和你给出的预期输出完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:27:03