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

基于行特定条件创建并修改Python Pandas DataFrame

Pandas DataFrame 数据清洗实现方案

原始数据

IDcountrymoneyothermoney_add
832932France121311982932
217#8#
1329T2
832932France30
31728#

修改规则

  • 若ID列包含#,该行保持不变;
  • 若ID列不含#且country为空(NaN),则为country列填充"Other",为other列填充0;
  • 最后,仅当money列为空(NaN)且other列有值时,从以下映射表匹配填充money和money_add字段。

映射表

other_IDmoneymoney_add
194532723823
501213238232
181813273283
30131383293
089323920

目标结果

IDcountrymoneyothermoney_add
832932France121311982932
217#8#
1329T2Other893203920
832932France13133083293
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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:01:07