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

如何在DataFrame中按多条件创建新列并填充工作中心名称?

工作中心标识向下填充实现(含逐行遍历版)

逐行遍历实现(符合需求)

先看模拟的DataFrame结构:

import pandas as pd

# 模拟你的数据结构
df = pd.DataFrame({
    'Column1': ['WC1', '', '', 'WC2', '', ''],
    'Column2': [None, None, None, None, None, None]
})

逐行遍历的核心逻辑:用变量记录当前有效的工作中心标识,遍历每一行时,若碰到新的工作中心(Column1中WC开头的有效值)就更新变量,否则将当前变量值填充到Column2:

current_wc = None

for idx, row in df.iterrows():
    # 检测到新的工作中心标识时更新当前值
    if pd.notna(row['Column1']) and row['Column1'].startswith('WC'):
        current_wc = row['Column1']
    # 填充当前行的Column2
    df.at[idx, 'Column2'] = current_wc

执行后得到的结果:

Column1Column2
WC1WC1
WC1
WC1
WC2WC2
WC2
WC2

更高效的pandas内置方法(可选)

如果数据量较大,逐行遍历效率偏低,推荐用pandas内置的ffill()(向前填充)方法,一行代码完成:

# 先把Column1的空值转为NaN,再向前填充赋值给Column2
df['Column2'] = df['Column1'].replace('', pd.NA).ffill()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 05:29:52