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

基于Org列填充Pandas缺失数据的高效实现方案求助

基于Org ID填充Pandas DataFrame缺失值

问题背景

我有一个包含缺失值的Pandas DataFrame,其中col1(整数类型)和col3(字符串类型)存在空值,且同一个Org ID(col2列)对应的这两列数据始终一致,需要基于Org列批量填充缺失值。

初始数据

import pandas as pd
import numpy as np

numbers = [np.nan, 5, 5, 5, np.nan,55,np.nan,55,55,np.nan,555,np.nan,555,555,np.nan]
Org = [1, 1, 1, 1, 1,2, 2, 2, 2, 2,3, 3, 3, 3, 3]
level3 = ["test", np.nan, "test", "test", np.nan, "failed", np.nan, "failed", "failed", "failed",np.nan,'try harder','try harder',np.nan,np.nan]
d = {'col1': numbers, 'col2': Org,'col3':level3}
initial = pd.DataFrame(data = d)

期望输出

numbers = [5, 5, 5, 5, 5,55,55,55,55,55,555,555,555,555,555]
Org = [1, 1, 1, 1, 1,2, 2, 2, 2, 2,3, 3, 3, 3, 3]
level3 = ["test", "test", "test", "test", "test", "failed", "failed", "failed", "failed", "failed",'try harder','try harder','try harder','try harder','try harder']
d = {'col1': numbers, 'col2': Org,'col3':level3}
final = pd.DataFrame(data = d)

我曾尝试用冗长的循环匹配Org ID填充非空值,但效率极低,寻求高效解决技巧。


高效解决方案

方法1:GroupBy + Transform取分组首个非空值

利用groupby按Org ID分组,结合transform('first')获取每个分组的首个非空值,自动填充该分组内的所有空值:

# 填充col1的缺失值
initial['col1'] = initial.groupby('col2')['col1'].transform('first')
# 填充col3的缺失值
initial['col3'] = initial.groupby('col2')['col3'].transform('first')

方法2:GroupBy + 前后填充(ffill + bfill)

先对分组内的空值向前填充,再向后填充,确保所有空值被覆盖:

# 填充col1
initial['col1'] = initial.groupby('col2')['col1'].ffill().bfill()
# 填充col3
initial['col3'] = initial.groupby('col2')['col3'].ffill().bfill()

优势说明

这两种方法都是Pandas的向量化操作,避免了Python循环的逐行处理开销,在大数据量下性能优势明显。由于每个Org ID对应的目标列数据一致,两种方法都能精准完成填充。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 06:45:28