如何用同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_id | buffer_id | easting | northing | year | ndvi |
|---|---|---|---|---|---|
| A | on | 111 | 444 | 1990 | 12 |
| B | on | 222 | 555 | 1995 | 22 |
| C | on | 333 | 666 | 2000 | 32 |
| A | off | 111 | 444 | 1990 | 42 |
| B | off | 222 | 555 | 1995 | 52 |
| C | off | 333 | 666 | 2000 | 62 |
如果存在同一个site_id对应多个buffer_id='on'的行,可根据业务需要先对'on'行做聚合(取第一个值、平均值等),再生成映射表即可。
内容的提问来源于stack exchange,提问作者vancaron
相关产品推荐
相关产品推荐

