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

基于条件在Pandas DataFrame中添加或更新指定行数据

处理DataFrame的Origin记录补全需求

初始数据

import pandas as pd
data = { 'Name_Type': ["Primary", "Primary", "AKA", "Primary"],
         'Name': ["John", "Daniel", "Dan", "Bob"],
         'Surname': ["Green", "Brown", "Brown", "White"],
         'Country Type': ["Origin", "Origin", None, "Origin"],
         'Country': ["UK", "UK", None, "UK"],
         'Other': ["Info", None, None, "Info"]}
df = pd.DataFrame(data)

初始输出:

Name_Type    Name Surname Country Type Country Other
0   Primary    John   Green       Origin      UK  Info
1   Primary  Daniel   Brown       Origin      UK  None
2       AKA     Dan   Brown         None    None  None
3   Primary     Bob   White       Origin      UK  Info

需求

对每一行Country Type为Origin的记录:

  • 若其下一行的Country Type和Country均为None,则将该行的Country Type改为Citizenship、Country设为UK,同时把Name和Surname替换为当前Origin行的值
  • 若不存在这样的下一行,则在当前行下方新增一行,设置Country Type为Citizenship、Country为UK,其余字段为None

期望输出

Name_Type    Name Surname Country Type Country Other
0   Primary    John   Green       Origin      UK  Info
1      None    None    None  Citizenship      UK  None
2   Primary  Daniel   Brown       Origin      UK  None
3       AKA  Daniel   Brown  Citizenship      UK  None
4   Primary     Bob   White       Origin      UK  Info
5      None    None    None  Citizenship      UK  None

解决方案

import pandas as pd

# 初始化数据
data = { 'Name_Type': ["Primary", "Primary", "AKA", "Primary"],
         'Name': ["John", "Daniel", "Dan", "Bob"],
         'Surname': ["Green", "Brown", "Brown", "White"],
         'Country Type': ["Origin", "Origin", None, "Origin"],
         'Country': ["UK", "UK", None, "UK"],
         'Other': ["Info", None, None, "Info"]}
df = pd.DataFrame(data)

result = df.copy()
# 倒序遍历,避免插入新行影响后续索引判断
for idx in reversed(df.index):
    current_row = df.loc[idx]
    if pd.notna(current_row['Country Type']) and current_row['Country Type'] == 'Origin':
        next_idx = idx + 1
        # 检查下一行是否存在且符合条件
        if next_idx < len(df):
            next_row = df.loc[next_idx]
            if pd.isna(next_row['Country Type']) and pd.isna(next_row['Country']):
                # 修改目标行
                result.loc[next_idx, ['Country Type', 'Country']] = ['Citizenship', 'UK']
                result.loc[next_idx, ['Name', 'Surname']] = current_row[['Name', 'Surname']]
                continue
        # 插入新行
        new_row = pd.Series({
            'Name_Type': None,
            'Name': None,
            'Surname': None,
            'Country Type': 'Citizenship',
            'Country': 'UK',
            'Other': None
        })
        # 拆分DataFrame并合并插入新行
        result = pd.concat([
            result.iloc[:idx+1],
            pd.DataFrame([new_row]),
            result.iloc[idx+1:]
        ], ignore_index=True)

print(result)

说明

  • 倒序遍历:从最后一行往前遍历,这样插入新行时不会打乱未处理行的索引,避免逻辑错误
  • 条件匹配:精准判断下一行是否为空白的Country相关字段,再决定修改还是新增
  • 字段同步:对已有空白行的情况,同步Origin行的姓名信息,匹配示例中的处理逻辑
  • 索引重置:用ignore_index=True确保插入后索引连续

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:15:55