基于指定条件更新Pandas DataFrame中的列数据
Pandas DataFrame 条件关联更新实现
需求说明
现有主 DataFrame 如下:
| ID | country | money | code | money_add | other |
|---|---|---|---|---|---|
| 832932 | Other | NaN | 00000 | NaN | NaN |
| 217#8# | NaN | NaN | NaN | NaN | NaN |
| 1329T2 | France | 12131 | 00020 | 3452 | 123 |
| 124932 | France | NaN | 00016 | NaN | NaN |
| 194022 | France | NaN | 00000 | NaN | NaN |
另有一张关联表:
| cod_t | money | money_add | other |
|---|---|---|---|
| 00000 | 4532 | 72323 | 321 |
| 00016 | 1213 | 23822 | 843 |
| 00018 | 1313 | 8393 | 183 |
| 00020 | 1813 | 27328 | 128 |
| 00030 | 8932 | 3204 | 829 |
需实现:当主表中 code 列不为空且 money 列为空时,以主表的code列和关联表的cod_t列为关联键,将关联表的money、money_add、other值更新到主表对应行。
更新后的预期结果:
| ID | country | money | code | money_add | other |
|---|---|---|---|---|---|
| 832932 | Other | 4532 | 00000 | 72323 | 321 |
| 217#8# | NaN | NaN | NaN | NaN | NaN |
| 1329T2 | France | 12131 | 00020 | 3452 | 123 |
| 124932 | France | 1213 | 00016 | 23822 | 843 |
| 194022 | France | 4532 | 00000 | 72323 | 321 |
实现代码
通过merge结合条件筛选完成更新,代码如下:
import pandas as pd # 构造主表 main_df = pd.DataFrame({ 'ID': ['832932', '217#8#', '1329T2', '124932', '194022'], 'country': ['Other', None, 'France', 'France', 'France'], 'money': [None, None, 12131, None, None], 'code': ['00000', None, '00020', '00016', '00000'], 'money_add': [None, None, 3452, None, None], 'other': [None, None, 123, None, None] }) # 构造关联表 lookup_df = pd.DataFrame({ 'cod_t': ['00000', '00016', '00018', '00020', '00030'], 'money': [4532, 1213, 1313, 1813, 8932], 'money_add': [72323, 23822, 8393, 27328, 3204], 'other': [321, 843, 183, 128, 829] }) # 筛选需要更新的行 mask = main_df['code'].notna() & main_df['money'].isna() # 关联获取更新值 updated_part = main_df[mask].merge( lookup_df, left_on='code', right_on='cod_t', how='left', suffixes=('', '_new') ) # 更新目标列 updated_part['money'] = updated_part['money_new'] updated_part['money_add'] = updated_part['money_add_new'] updated_part['other'] = updated_part['other_new'] # 保留原表列结构 updated_part = updated_part[main_df.columns] # 合并更新部分与未更新部分,恢复原顺序 final_df = pd.concat([main_df[~mask], updated_part]).sort_index() print(final_df)
运行代码后即可得到预期的更新结果。
内容的提问来源于stack exchange,提问作者Carola
相关产品推荐
相关产品推荐

