基于行特定条件创建并修改Python Pandas DataFrame
Pandas DataFrame 数据清洗实现方案
原始数据
| ID | country | money | other | money_add |
|---|---|---|---|---|
| 832932 | France | 12131 | 19 | 82932 |
| 217#8# | ||||
| 1329T2 | ||||
| 832932 | France | 30 | ||
| 31728# |
修改规则
- 若ID列包含
#,该行保持不变; - 若ID列不含
#且country为空(NaN),则为country列填充"Other",为other列填充0; - 最后,仅当money列为空(NaN)且other列有值时,从以下映射表匹配填充money和money_add字段。
映射表
| other_ID | money | money_add |
|---|---|---|
| 19 | 4532 | 723823 |
| 50 | 1213 | 238232 |
| 18 | 1813 | 273283 |
| 30 | 1313 | 83293 |
| 0 | 8932 | 3920 |
目标结果
| ID | country | money | other | money_add |
|---|---|---|---|---|
| 832932 | France | 12131 | 19 | 82932 |
| 217#8# | ||||
| 1329T2 | Other | 8932 | 0 | 3920 |
| 832932 | France | 1313 | 30 | 83293 |
| 31728# |
Python 实现代码
import pandas as pd import numpy as np # 构造原始DataFrame df = pd.DataFrame({ 'ID': ['832932', '217#8#', '1329T2', '832932', '31728#'], 'country': ['France', np.nan, np.nan, 'France', np.nan], 'money': [12131, np.nan, np.nan, np.nan, np.nan], 'other': [19, np.nan, np.nan, 30, np.nan], 'money_add': [82932, np.nan, np.nan, np.nan, np.nan] }) # 构造映射表并转为字典,提升匹配效率 mapping_df = pd.DataFrame({ 'other_ID': [19, 50, 18, 30, 0], 'money': [4532, 1213, 1813, 1313, 8932], 'money_add': [723823, 238232, 273283, 83293, 3920] }) mapping_dict = mapping_df.set_index('other_ID').to_dict('index') # 1. 标记ID含#的行,后续跳过处理 has_hash_mask = df['ID'].str.contains('#', na=False) # 2. 处理ID不含#且country为空的行 no_hash_no_country_mask = ~has_hash_mask & df['country'].isna() df.loc[no_hash_no_country_mask, ['country', 'other']] = ['Other', 0] # 3. 处理money为空且other有值的行 money_nan_other_valid_mask = df['money'].isna() & df['other'].notna() for idx, row in df[money_nan_other_valid_mask].iterrows(): other_val = row['other'] if other_val in mapping_dict: df.loc[idx, 'money'] = mapping_dict[other_val]['money'] df.loc[idx, 'money_add'] = mapping_dict[other_val]['money_add'] # 查看处理后的结果 print(df)
代码说明
- 用**掩码(mask)**精准定位需要处理的行,避免不必要的遍历;
- 将映射表转为字典,大幅提升匹配速度;
- 分步骤对应需求,逻辑清晰易维护。
内容的提问来源于stack exchange,提问作者Carola
相关产品推荐
相关产品推荐

