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

如何在DataFrame中保留每组game_id的首行并删除其余行?

用for/if循环保留DataFrame每个game_id的首行数据

先构造你提供的示例DataFrame:

import pandas as pd

data = {
    'game id': [1,1,1,1,2,2,2,2],
    'score': [55,59,62,71,74,65,89,98]
}
df = pd.DataFrame(data)

按照你的要求,用for和if循环实现保留每个game_id的第一行、删除其余行的代码如下:

# 记录已经处理过的game_id,避免重复保留
seen_game_ids = set()
# 存储需要删除的行索引
drop_indices = []

# 遍历DataFrame的每一行
for idx, row in df.iterrows():
    current_id = row['game id']
    # 如果当前game_id已经保留过首行,标记该行待删除
    if current_id in seen_game_ids:
        drop_indices.append(idx)
    else:
        # 首次遇到该game_id,加入集合并保留该行
        seen_game_ids.add(current_id)

# 一次性删除所有标记的行,重置索引
result_df = df.drop(drop_indices).reset_index(drop=True)
print(result_df)

运行后得到的结果就是你期望的:

game id  score
0        1     55
1        2     74

额外提一句:其实pandas自带更简洁的实现方式df.groupby('game id').first().reset_index(),但既然你指定要用循环,上面的代码完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:31:13