如何循环遍历pandas DataFrame列动态应用条件实现批量过滤赋值
动态遍历pandas列批量应用np.select条件的实现方案
核心解决思路:你之前定义的condition是固定绑定B1列判断逻辑的常量,只需在每次循环遍历到对应列时,基于当前列动态生成条件列表即可。
另外注意你原有代码里的笔误:isnull是pandas Series的内置方法,必须加括号调用,直接写df['B1'].isnull==False判断的是方法对象本身的布尔值,会导致逻辑错误,需修正为~df[列名].isnull()的写法。
直接实现代码
import pandas as pd import numpy as np # 示例数据构造 df = pd.DataFrame({ 'B1': [9,8,0,1], 'B2': [0,7,9,0], 'B3': [5,6,8,7], 'B4': [6,4,6,6], 'B5': [7,8,6,3] }) values = [999, 444, 555] # 循环遍历所有列动态处理 for col in df.columns: # 基于当前列生成条件列表 condition = [ (df[col] == 0) | (~df[col].isnull()), (df[col] == 8) | (df[col].isnull()), (df[col] == 6) | (~df[col].isnull()) ] df[col] = np.select(condition, values)
更易维护的函数式写法
如果后续需要频繁调整条件规则,可以把条件逻辑提前封装为函数列表,循环时直接调用生成当前列的条件即可:
# 提前封装条件逻辑,后续修改只需调整这部分 cond_funcs = [ lambda x: (x == 0) | (~x.isnull()), lambda x: (x == 8) | (x.isnull()), lambda x: (x == 6) | (~x.isnull()) ] values = [999, 444, 555] for col in df.columns: current_cond = [func(df[col]) for func in cond_funcs] df[col] = np.select(current_cond, values)
以上两种写法都会对所有列应用和原来B1列完全一致的判断规则,运行效果和你逐列手动处理的结果完全一致。
内容的提问来源于stack exchange,提问作者James Lin
相关产品推荐
相关产品推荐

