You need to enable JavaScript to run this app. 数据集中存在重复ID 如何保留各ID下NA值最少的对应行
优惠活动
大模型
产品
解决方案
定价
更多

数据集中存在重复ID 如何保留各ID下NA值最少的对应行

问题解决代码(Python Pandas)

实现逻辑

  • 新增临时列统计每行的NA数量
  • 按id字段分组,筛选每组内NA数量最少的行
  • 清理临时字段得到最终结果

完整可运行代码

import pandas as pd
import numpy as np

# 构造示例数据
data = [
    [123, 10, np.nan, np.nan, 3],
    [123, 50, 3, 2, np.nan],
    [124, 30, 5, 7, np.nan],
    [124, 30, 8, 1, 2]
]
df = pd.DataFrame(data, columns=['id', 'Col1', 'col1 2', 'col 3', 'col 4'])

# 计算每行的NA数量
df['na_count'] = df.isna().sum(axis=1)

# 方法1:保留所有NA数量最少的行(如果同id下有多行NA数相同则全部保留)
result = df[df.groupby('id')['na_count'].transform('min') == df['na_count']].drop('na_count', axis=1)

# 方法2:仅保留1行NA最少的行(如果同id下有多行NA数相同则取排序后第一个)
# result = df.sort_values('na_count', ascending=True).groupby('id', as_index=False).first().drop('na_count', axis=1)

print(result)

运行输出结果

id  Col1  col1 2  col 3  col 4
1  123    50     3.0    2.0    NaN
3  124    30     8.0    1.0    2.0

完全匹配你要求的保留ID为123的第二行、ID为124的第二行的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 00:54:04