如何实现Pandas DataFrame指定列按状态条件逐行替换值
实现方案
首先导入依赖、构建测试数据:
import pandas as pd # 原始数据,补全了原代码缺失的右括号 data = [["nota", "b"], ["notb", "nota"], ["a", "b"], ["a", "notb"], ["notb", "notb"], ["nota", "notb"], ["nota", "nota"], ["notb", "a"], ["b", "notb"], ["b", "a"], ["nota", "nota"], ["notb", "b"]] df = pd.DataFrame(data, columns = ["status1", "status2"])
核心逻辑实现
先编写单列处理函数,再对指定列批量应用即可:
def process_single_column(col): result = [] # 状态标记:初始等待a或b,可选取值为 'ab' / 'nota' / 'notb' wait_target = 'ab' for value in col: current_output = 'empty' if wait_target == 'ab': # 等待a/b阶段,命中则保留,切换到等待对应not值 if value in ('a', 'b'): current_output = value wait_target = f'not{value}' else: # 等待对应not值阶段,命中则保留,切换回等待a/b if value == wait_target: current_output = value wait_target = 'ab' result.append(current_output) return pd.Series(result, index=col.index) # 对指定列应用处理逻辑,这里示例处理status1和status2两列 target_cols = ['status1', 'status2'] df[target_cols] = df[target_cols].apply(process_single_column)
输出验证
运行后打印print(df)即可得到你期望的结果:
status1 status2 0 empty b 1 empty empty 2 a empty 3 empty notb 4 empty empty 5 nota empty 6 empty empty 7 empty a 8 b empty 9 empty empty 10 empty nota 11 notb b
内容的提问来源于stack exchange,提问作者GC2023
相关产品推荐
相关产品推荐

