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

如何用同site_id的其他行对应值填充pandas DataFrame缺失值

Pandas按site_id匹配填充缺失值实现方案

你需要将buffer_id为'off'的行中easting、northing、year三列的缺失值(含字符串'NaN'、数值-9999),用同site_id下buffer_id为'on'行的对应值填充,完整可运行代码如下:

import pandas as pd

# 示例DataFrame
df = pd.DataFrame({'site_id': ['A', 'B', 'C', 'A', 'B', 'C'],
               'buffer_id': ['on', 'on', 'on', 'off', 'off', 'off'],
               'easting': [111, 222, 333, 'NaN', 'NaN', 'NaN'],
               'northing': [444, 555, 666, 'NaN', 'NaN', 'NaN'],
               'year': [1990, 1995, 2000, -9999, -9999, -9999],
               'ndvi': [12, 22, 32, 42, 52, 62]})

# 定义需要填充的目标列
fill_cols = ['easting', 'northing', 'year']

# 第一步:统一将字符串'NaN'、数值-9999替换为pandas标准缺失值格式
df[fill_cols] = df[fill_cols].replace(['NaN', -9999], pd.NA)

# 第二步:提取buffer_id为'on'的行构建填充映射表,以site_id为索引
on_fill_map = df[df['buffer_id'] == 'on'].set_index('site_id')[fill_cols]

# 第三步:仅对buffer_id为'off'的行做匹配填充,不修改'on'行原有数据
df.loc[df['buffer_id'] == 'off', fill_cols] = df.loc[df['buffer_id'] == 'off', 'site_id'].map(on_fill_map.to_dict('index'))

运行结果说明

填充后所有buffer_id='off'的行对应字段会被替换为同site_id下'on'行的数值,ndvi等非目标列不受影响,最终输出如下:

site_idbuffer_ideastingnorthingyearndvi
Aon111444199012
Bon222555199522
Con333666200032
Aoff111444199042
Boff222555199552
Coff333666200062

如果存在同一个site_id对应多个buffer_id='on'的行,可根据业务需要先对'on'行做聚合(取第一个值、平均值等),再生成映射表即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:09:03