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

如何合并Pandas DataFrame中同ID行的非空数据?

需求与解决方案

问题描述

我有一个包含id、single、age三列的Pandas DataFrame,原始数据如下:

data = {
    'id': [1, 1, 1, 2, 2, 3, 3, 4],
    'single': ['y', '', '', '', 'n', 'n', '', 'y'],
    'age': ['', 22, '', 34, '', 22, '', 43]
}

同一id的部分行存在空值,其余行包含有效信息,希望将其处理为如下形式:

result_data = {
    'id': [1,2,3,4],
    'single': ['y', 'n', 'n', 'y'],
    'age': [22, 34, 22, 43]
}

请问是否可以实现该需求?

解决方案

完全可以实现,核心逻辑是按id分组后提取每组内的非空有效值,具体实现步骤如下:

步骤1:构造DataFrame并替换空字符串

首先将原始数据转为DataFrame,同时把空字符串替换为NaN(Pandas的聚合函数对NaN处理更便捷):

import pandas as pd
import numpy as np

# 构造原始DataFrame
df = pd.DataFrame({
    'id': [1, 1, 1, 2, 2, 3, 3, 4],
    'single': ['y', '', '', '', 'n', 'n', '', 'y'],
    'age': ['', 22, '', 34, '', 22, '', 43]
})

# 替换空字符串为NaN
df = df.replace('', np.nan)

步骤2:按id分组聚合

利用groupby按id分组,再通过first()函数提取每组内的第一个非空值(因为同一id下有效信息唯一,max()/min()也能达到相同效果):

# 分组聚合,保留id作为列而非索引
result_df = df.groupby('id', as_index=False).first()

执行后得到的result_df就是目标格式的DataFrame,输出如下:

id single  age
0   1      y   22
1   2      n   34
2   3      n   22
3   4      y   43

步骤3:转为字典格式(可选)

如果需要转为你给出的字典格式,使用to_dict('list')方法即可:

result_data = result_df.to_dict('list')
print(result_data)

输出结果:

{'id': [1, 2, 3, 4], 'single': ['y', 'n', 'n', 'y'], 'age': [22, 34, 22, 43]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:12:19