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

如何格式化Pandas DataFrame,实现每个ID仅保留一行?

解决方法

你可以通过groupby按id分组,对特征列取最大值来实现需求——因为独热编码的特性是每行只有一个1,取最大值就能保留该id下是否出现过对应特征的标记。

代码示例

首先构造你的原始DataFrame:

import pandas as pd

df = pd.DataFrame({
    'id': ['A', 'A', 'B', 'B', 'B', 'C'],
    'feature1': [1, 0, 0, 1, 0, 0],
    'feature': [0, 1, 1, 0, 0, 0],
    'feature3': [0, 0, 0, 0, 1, 1]
})

然后执行聚合操作:

result_df = df.groupby('id').max().reset_index()

执行后result_df就是你想要的格式:

id  feature1  feature  feature3
0  A         1        1         0
1  B         1        1         1
2  C         0        0         1

补充说明

  • groupby('id')按id分组,把同一id的行归为一组
  • .max()对每组的特征列取最大值,刚好匹配独热编码的聚合需求(只要组内有1,结果就是1,否则0)
  • .reset_index()把id从索引变回普通列,和原始格式一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:50:39